PHP& MySQL:mysqli_num_rows()错误。怎么了?

时间:2018-04-04 16:04:37

标签: php mysql database search mysqli

我创建了这个代码,用于一次搜索多个单词,但我的代码不起作用。我自己纠正的方式中出现的大多数错误,但是这样做不起作用。

当我点击搜索按钮时,它会给我这个错误:

  

警告:mysqli_num_rows()要求参数1为mysqli_result,第26行的C:\ XAMPP \ htdocs \ test \ search.php中给出布尔值

这是我的代码:

<?php

$host = 'localhost';
$user = 'root';
$password = '';
$database = 'dictionary';

$connect = new mysqli ($host, $user, $password, $database);

if (isset($_GET['search'])) {
  $condition = '';
  $query = explode(" ", $_GET['search']);
  foreach ($query as $text)
  {
    $condition .= "hieroglyphs LIKE '%".mysqli_real_escape_string($connect, $text)."%' OR";
  }
  $condition = substr($condition, 0, -4);
  $sql_query = "SELECT hieroglyphs, meaning FROM test_dictionary WHERE " . $condition;
  $result = mysqli_query($connect, $sql_query);
  if (mysqli_num_rows($result) > 0)
  {
     echo "<table><tr><th>Hieroglyphs</th><th>Meaning</th></tr>";
     while($row = mysqli_fetch_array($result))
     {
         echo "<tr><td>".$row["hieroglyphs"]."</td><td>".$row["meaning"]."</td></tr>";
     }
     echo "</table>";
  } else {
     echo "0 results";
  }
}

$connect->close();

?>

如何更正此错误?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我所做的就是添加测试以确保我们的$result不为空。通过执行此操作,如果它为空,它将打印您的SQL语句以转移到您选择的PhpMyAdmin或其他数据库交互工具,以便您可以从那里调整查询。

<?php

$host = 'localhost';
$user = 'root';
$password = '';
$database = 'dictionary';

$connect = new mysqli ($host, $user, $password, $database);

if (isset($_GET['search'])) {
    $condition = '';
    $query = explode(" ", $_GET['search']);
    foreach ($query as $text) {
        $condition .= "hieroglyphs LIKE '%" . mysqli_real_escape_string($connect, $text) . "%' OR";
    }
    $condition = substr($condition, 0, -4);
    $sql_query = "SELECT hieroglyphs, meaning FROM test_dictionary WHERE " . $condition;
    $result = mysqli_query($connect, $sql_query);
    // if our result isn't empty, let's process
    if (!empty($result)) {
        if (mysqli_num_rows($result) > 0) {
            echo "<table><tr><th>Hieroglyphs</th><th>Meaning</th></tr>";
            while ($row = mysqli_fetch_array($result)) {
                echo "<tr><td>" . $row["hieroglyphs"] . "</td><td>" . $row["meaning"] . "</td></tr>";
            }
            echo "</table>";
        } else {
            echo "0 results";
        }
    } else {
        // If it is empty, we need to try and find out why.
        print "No results: " . $sql_query;
    }
}

$connect->close();

?>