【问题标题】:PHP - doesn`t show anything with mysqli_fetch_assoc in while-loopPHP - 在while循环中不显示mysqli_fetch_assoc的任何内容
【发布时间】:2017-08-28 22:14:31
【问题描述】:

我想通过 JSON 将 MySQL 数据库中的一些数据提供给 Android 应用程序。

到目前为止,我已经编写了这个 php 脚本来给我 JSON 对象:

$result = mysqli_query($con,"SELECT * FROM job");

$row = mysqli_fetch_assoc($result); 

while($row = mysqli_fetch_assoc($result)){
  $output[] = $row;
}

print(json_encode($output));

我偶然发现,当我不添加“$row = mysqli_fetch_assoc($result);”行时在while循环之前它不会返回任何东西。但是当我像示例中那样添加这一行时,JSON 对象不包含第一个元素。

我相信这是因为 $row 已经包含第一行的这一行。

希望你能帮助我:)

【问题讨论】:

  • 返回多少行?在查询后插入:echo mysqli_num_rows($result);。您必须删除$row=mysqli_fetch_assoc($result);这一行。
  • 不可能。 PHP 不在乎您在哪里/如何进行 fetch 调用。无论是在一段时间内还是在它之前,您仍然会从数据库中获取一行。你所做的只是扔掉第一行,除非你在while 开始之前还有$output[] = $row;
  • 当我不在 while 循环之前添加该行时,它不会返回任何内容 不可能.....
  • $rowwhile loop 之前得到的值是多少?

标签: php mysql json


【解决方案1】:

为了弄清楚您的查询有什么问题,您必须执行以下操作:

if ($result = mysqli_query($db, $sql)) {
    // Here you can see and check count of rows in your result set.
    $numRows = mysqli_num_rows($result);
    // ...
} else {
    // Here you can see and check and understand error.
    var_export(mysqli_error($db));
}

目的是遍历你必须做的结果集中的所有行:

while ($row = mysqli_fetch_assoc($result)) {
    var_export($row);
}

在while循环之前你不能有$row = mysqli_fetch_assoc($result)

【讨论】:

    猜你喜欢
    • 2011-05-25
    • 1970-01-01
    • 2013-03-01
    • 2020-08-05
    • 2017-07-05
    • 2016-10-28
    • 1970-01-01
    • 2016-03-29
    • 2019-11-07
    相关资源
    最近更新 更多