php - 如何将多个 SQL 结果放入数组中
问题描述
我无法让我的脚本工作,我不明白为什么。我想获取所有 SQL 结果并将它们放入一个数组中。我当前的脚本只返回一个结果。
我知道我需要使用循环,但我只是不知道如何将它与当前脚本集成。我已经阅读了 50 多篇文章,但我仍然无法工作。
<?php
$sql = "SELECT * FROM cart WHERE sess_id = '$sess_id'";
$result = mysqli_query($conn, $sql);
$count= mysqli_num_rows($result);
$items= array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
for($i=0;$i<$count;$i++)
{
$items = "{sku: "."'".$row["prod_sku"]."'".", quantity : ".$row["prod_qty"]."}, <br>";
}
}
}
echo $items."<br>";
?>
解决方案
它既简单又简单,您不需要在 while 循环内使用 for 循环。请使用以下代码,希望对您有所帮助。
$sql = "SELECT * FROM cart WHERE sess_id = '$sess_id'";
$result = mysqli_query($conn, $sql);
$items= array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$items[] = "{sku: "."'".$row["prod_sku"]."'".", quantity : ".$row["prod_qty"]."}, <br>";
}
}
// to print the array use the following command
// print_r($items);
// to echo the $items variable, you may encode it by json
echo json_encode($items);
谢谢。
推荐阅读
- react-native - 适用于 iOS 和 Android 的原生 Base 选择器,具有动态创建的项目列表
- python - 使用python将整数列添加到日期列以获取“未来日期”
- c# - 在 MovePosition 协程结束时防止刚体抖动
- redux-observable - Redux-Observable 调度多个动作并等待响应
- serialization - 如何强制 YamlDotNet 对所有多行字符串使用折叠块标量
- java - 需要帮助创建 10% 随机数组进行排序
- google-chrome - 新的 Chrome SameSite 更改如何影响旧 cookie?
- reactjs - 所有的 redux 动作都应该有相应的 reducer 吗?
- javascript - 在 React/Javascript 中格式化日期?
- sql - 有没有办法简化这个 SQL 函数?我觉得它是多余的