dpzp5127 2014-08-18 18:23
浏览 82
已采纳

strpos总是回归真实

My code always return "true" whatever the string is I tried a bunch of thing but they are only return false... I have no idea what I can do to fix this... my code:

public function isBlacklisted($string)
{
    $apis = mysql_connect("mysql.hostinger.fr", "mysql user", "testpass") or die(mysql_error());
    mysql_select_db("u770656121_api", $apis);
    $sql = "SELECT * FROM blacklist";
    $result = mysql_query($sql, $apis);
    while($row = mysql_fetch_array($result)) {
        $username = $row['username'];
        if (strpos($string,$username) !== 0) {
            return true;
            break;
        } else {
            return false;
            break;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • duancai7568 2014-08-18 18:25
    关注

    strpos returns false is it is not found, and 0 if it is in the first position of the string. It sounds like you want to do:

    if (strpos($string,$username) !== false) {
    

    Also, you are looping over the DB results, you should only return if it is found:

     while($row = mysql_fetch_array($result)) {
        $username = $row['username'];
        if (strpos($string,$username) !== false) {
            return true;
        }
     }
     return false;
    

    Or, even better:

    $sql = "SELECT * FROM blacklist WHERE 'username' LIKE '%$username%'";
    $result = mysql_query($sql, $apis);
    while($row = mysql_fetch_array($result)) {
       if ($row['username']) return true;
    }
    

    making sure to escape $username and ideally switching to mysqli or pdo instead of using deprecated mysql statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用