PHP MySQLi仅以JSON返回一行 [英] PHP MySQLi is just returning one row in JSON
本文介绍了PHP MySQLi仅以JSON返回一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理以下代码.为什么我的JSON输出中只有一行?
I am working on the below code. Why am I getting only one row in my JSON output?
$items = [];
if ($stmt = $this->conn->prepare("SELECT * FROM $tbl")) {
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$items = $row;
}
$stmt->free_result();
$stmt->close();
}
$this->conn->close();
}
echo json_encode($items);
推荐答案
之所以会发生这种情况,是因为您要遍历所有行并将每个行分配给$items
:
This happens because you are going through the rows and assigning each of them to $items
:
while ($row = $result->fetch_assoc()) {
$items = $row;
}
因此,在循环结束后,您将得到一个变量,该变量是在该循环的最后一次迭代期间分配的$ row.
So after the loop is finished you end up with a variable which is a $row that was assigned during the last iteration of that loop.
您需要将值推入数组,如下所示:
You would need to push the values to an array like so:
$items[] = $row;
这篇关于PHP MySQLi仅以JSON返回一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文