【问题标题】:mysqli_fetch_assoc() not workingmysqli_fetch_assoc() 不工作
【发布时间】:2015-03-23 09:55:44
【问题描述】:

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

<?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 函数处停止工作。

【问题讨论】:

  • 究竟是什么不工作?你连接到数据库?你的结果不是预期的吗?你有一个 php 错误?
  • WHERE 关键字 LIKE ,而不是 '=',除非您希望得到两端都带有百分号的字符串
  • @0x1gene 我可以很好地连接到数据库。正如标题所说,问题出在mysqli_fetch_assoc 函数上。该函数返回die 字符串。
  • @n-dru 替换为LIKE 没有区别。
  • 另外,不要打印自定义错误消息,而是使用or die(mysqli_error())。这将帮助您识别错误。

标签: php mysqli


【解决方案1】:

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

【讨论】:

  • 我使用了路径,因为使用相对路径会返回failed to open stream: No such file or directory,但我已经进入浏览器中的目录。
  • &lt;?php $con = mysqli_connect("localhost", "&lt;USERNAME&gt;", "&lt;PASSWORD&gt;", "&lt;DB&gt;") or die("&lt;p color=\"#f00\"&gt;Could not connect to database.&lt;/p&gt;"); ?&gt;
【解决方案2】:

替换这些行:

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

【讨论】:

  • 返回“null”,如果添加了die,则返回die字符串。
【解决方案3】:

我在一个带有一个值的简单表上遇到了同样的问题,我添加了 die 错误消息,但它仍然对我没有任何显示,尝试回显表的一个特定行,对我来说它确实显示了一个结果,所以我认为我的问题在于编码为 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']);
   }
}

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多