mysqli_fetch_assoc() not working


mysqli_fetch_assoc() not working

有人能调试一下并告诉我为什么is不工作吗?

<?php
include("C:'Wamp'www'system'db'connect.php");
$term = mysqli_real_escape_string($con, $_GET['q']);
echo "results for '"".$term."'".<br>";
$sql = "SELECT * FROM `search` WHERE Keywords='%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die("<p color='"#f00'">Could not query database.</p>");
while($row = mysqli_fetch_assoc($result) or die("<p color='"#f00'">Could not fetch assoc array in database.</p>")) {
    echo $row['Title'];
}
echo json_encode($row['Title']);
mysqli_close($con);
?>

它在mysqli_fetch_assoc功能上停止工作。

如注释中所述,您应该打印实际的mysql错误消息,而不是自定义消息,这将帮助您调试错误,

以下是一些修复您的错误的建议,

您的代码应该是:

<?php
include("C:'Wamp'www'system'db'connect.php"); //<-- You should give relative path instead of this one
$term = mysqli_real_escape_string($con, $_GET['q']);
echo "results for '"".$term."'".<br>";
$sql = "SELECT * FROM `search` WHERE Keywords like '%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die(mysqli_error($con)); //<-- show mysql error instead of custom one
while($row = mysqli_fetch_assoc($result) ) {
    echo $row['Title'];
}
echo json_encode($row['Title']);
mysqli_close($con);
?>

替换这些行:

$sql = "SELECT * FROM `search` WHERE Keywords='%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die("<p color='"#f00'">Could not query database.</p>");
while($row = mysqli_fetch_assoc($result) or die("<p color='"#f00'">Could not fetch assoc array in database.</p>")) {
   echo $row['Title'];
}

这些:

$sql = "SELECT * FROM `search` WHERE Keywords LIKE '%{$term}%' LIMIT 10";
$result = mysqli_query($con, $sql) or die("<p color='"#f00'">Could not query database.</p>");
while($row = mysqli_fetch_assoc($result) ) {
   echo $row['Title'];
}

我在一个只有一个值的简单表上遇到了同样的问题,我添加了die错误消息,但它仍然对我没有显示任何内容,试着回显表中的一个特定行,对我来说,它确实显示了一个结果,所以我认为我的问题在于编码为json。所以我使用json编码中的解决方案返回空字符串至于你特定行的回声,我试过了:

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if($result->num_rows > 0){
     while($row= mysqli_fetch_assoc($result)){
        echo($row['name_ofRow']);
   }
}

我希望这能对一些人有所帮助。