我需要显示名为 cart 的表中的所有产品。但是,无论表中有多少产品,json_decode
总是在用户端返回一个包含 1 个产品的数组(检查 var_dump)。用户只能看到最后添加的产品。 json 只显示表的最后一行。我需要它来展示所有产品。我尝试了很多方法来调试这个应用程序,但我认为我没有完全理解 json 功能。
var_dump($items) : array(1) { [0]=> array(4) { ["id"]=> string(2) "14"["size"]=> string(1) "0"["quantity"]=> string(1) "1"["available"]=> string(1) "1"} }
cart.php
<?php
if($cart_id !=''){
$cartQ = $db->query("SELECT * FROM cart WHERE id ='{$cart_id}' ");
$result = mysqli_fetch_assoc($cartQ);
$items = json_decode($result['items'],true);
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<?php
foreach($items as $item){
var_dump($items);
$product_id = $item['id'];
$productQuery = $db->query("SELECT * FROM product WHERE id ='{$product_id}' ");
$product = mysqli_fetch_assoc($productQuery);
?>
<tr class="p">
<td class="image"><img src="<?=$product['image_1'];?>" /></td>
<td class="name"><?=$product['prod_name'];?></td>
<td class="price"><?=money($product['price']);?></td>
<td class="quantity"> <?=$item['quantity'];?></td>
<td class="pricesubtotal"><?=money($item['quantity'] * $product['price'] );?></td>
<td class=""><div><button name='removeitem' onclick="update_cart('removeitem','<?=$product_id['id'];?>');">×</button></div></td>
</tr>
<?php endif;?>
最佳答案
您的数据有很多问题。首先,您不应该将项目保存为 json。或者至少您不应该将项目 ID 保存在 json 对象中。然后,您将能够利用久负盛名的 INNER JOIN 以最少的代码和非常快的速度非常轻松地获取所有产品。
SELECT * FROM products INNER JOIN cart on cart.item_id = product.id
WHERE cart.id = ?
作为旁注,您应该为查询使用准备好的语句而不是字符串连接。
关于php - json_decode 使用 mysqli 返回数组 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133153/