我無法讓我的腳本工作,我不明白為什么。我想獲取所有 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>"; ?>
1 回答

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
它既簡單又簡單,您不需要在 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);
謝謝。
- 1 回答
- 0 關注
- 185 瀏覽
添加回答
舉報
0/150
提交
取消