[英]PHP MySQLi select from database and push to json
$q = $db->query("SELECT * FROM user");
while($row = mysqli_fetch_array($q)) {
$product = array();
$product['id'] = $row['id'];
$product['user'] = $row['user'];
$product['data'] = $row['data'];
}
$response["product"] = array();
array_push($response["product"], $product);
I have been trying to select from a database the entire table and then loop through each result and push it to an array. 我一直在尝试从数据库中选择整个表,然后遍历每个结果并将其推入数组。 The above code only seems to put to the array the last item in the table.
上面的代码似乎只将表中的最后一项放入数组。
You're probably better off doing something like this: 您最好这样做:
$q = $db->query("SELECT * FROM user");
$response = array();
$response["product"] = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'id' => $row['id'],
'user' => $row['user'],
'data' => $row['data'],
);
array_push($response["product"], $product);
}
You were only getting the last item because you kept resetting your $response['product']
& $product
array. 您只得到最后一个项目,因为您一直在重置
$response['product']
和$product
数组。
You need to push into the array for each item. 您需要将每个项目推入数组。 At the moment you overwrite
$product
each time though the loop. 此刻,您每次都通过循环覆盖
$product
。 Try this: 尝试这个:
$q = $db->query("SELECT * FROM user");
$response["product"] = array();
while($row = mysqli_fetch_array($q)) {
$product = array();
$product['id'] = $row['id'];
$product['user'] = $row['user'];
$product['data'] = $row['data'];
array_push($response["product"], $product);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.