首页 文章

PHP和MySQL - 警告:mysqli_num_rows()期望参数1是mysqli_result,布尔给定[重复]

提问于
浏览 849
2

可能重复:mysql_fetch_array()期望参数1是资源,在select中给出布尔值

我想知道如何纠正我在下面列出的错误 .

我收到以下错误 .

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given on line 159

第159行是

$foundnum = mysqli_num_rows($run);

这是PHP和MySQL代码的一部分 .

mysqli_select_db($mysqli, "sitename");

        $search_explode = explode(" ", $search);

        foreach($search_explode as $search_each) {
            $x++;
            if($x == 1){
                $construct .= "(users_comments.article_content LIKE '%$search_each%' OR users_comments.title LIKE '%$search_each%' OR users_comments.summary LIKE '%$search_each%')";
            } else {
                $construct .= "(OR users_comments.article_content LIKE '%$search_each%' OR users_comments.title LIKE '%$search_each%' OR users_comments.summary LIKE '%$search_each%')";
            }

        }

        $construct = "SELECT users.*, users_comments.* FROM users INNER JOIN users_comments ON users.user_id = users_comments.user_id WHERE $construct ORDER BY users_comments.date_created DESC";
        $run =  mysqli_query($mysqli, $construct);

        $foundnum = mysqli_num_rows($run);

    if ($foundnum == 0) {
        echo 'No results found.';
    }

2 回答

  • 3

    你必须测试 $run 以确保 mysqli_query() 没有返回false .

    if ($run != false) {
      $foundnum = mysqli_num_rows($run);
      if ($foundnum == 0) {
        echo 'No results found.';
      }
    }
    
  • 2

    这是因为

    if ( $result = mysqli_query($mysqli, $construct) ) {
        // got something!
        }
    

    返回FALSE . 在将其用作结果集之前,必须测试返回值 . 您的SQL语句中必定有错误 .

    小建议:为避免在循环中重复复杂的SQL字符串,请使用$ prefix变量,如下所示:

    $prefix = '';
    foreach($search_explode as $search_each) {
        $construct .=  "$prefix (users_comments.article_content LIKE '%$search_each%' OR users_comments.title LIKE '%$search_each%' OR users_comments.summary LIKE '%$search_each%') ";
        $prefix = ' OR' ;
    }
    

    我怀疑错误是无论如何,你把'OR'放在括号内,而不是在外面 .

相关问题