mysqli_fetch_assoc()不起作用

时间:2015-03-23 09:55:45

标签: php mysqli

有人可以调试这个并告诉我为什么不起作用吗?

<?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功能工作。

3 个答案:

答案 0 :(得分:0)

如评论中所述,您应该打印实际的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);
?>

答案 1 :(得分:0)

替换这些行:

$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'];
}

答案 2 :(得分:0)

我在一个带有一个值的简单表上遇到了同样的问题,我添加了模具错误消息,它仍然没有显示任何内容,尝试回显您表的一个特定行,对我来说它确实显示了结果,所以我认为我的问题在于编码为json。 所以我使用json encoding returning empty string中找到的解决方案 至于你的特定行的回声,我尝试了这个:

$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']);
   }
}

我希望这会有所帮助。