繁体   English   中英

json_decode使用mysqli返回1的数组

[英]json_decode return array of 1 with mysqli

我需要显示名为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'];?>');">&times</button></div></td>
  </tr>
  <?php endif;?>

您的数据存在很多问题。 首先,你不应该将项目保存为json。 或者至少你不应该在json对象中保存item id。 然后,您将能够利用久负盛名的INNER JOIN轻松获得所有产品,并且代码最少且速度非常快。

SELECT * FROM products INNER JOIN cart on cart.item_id = product.id
WHERE cart.id = ?

作为旁注,您应该使用预准备语句而不是字符串concat来进行查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM