简体   繁体   English

json_decode使用mysqli返回1的数组

[英]json_decode return array of 1 with mysqli

I need to display all products from a table called cart. 我需要显示名为cart的表格中的所有产品。 However, no matter how many products there are on the table, json_decode always return an array of 1 product on user side (check the var_dump). 但是,无论表上有多少产品, json_decode总是在用户端返回1个产品的数组(检查var_dump)。 The user can only see last product added. 用户只能看到添加的最新产品。 json only shows last row of table. json只显示表的最后一行。 I need it to show all products. 我需要它来显示所有产品。 I have tried many things to debug this app but I think im not fully understanding json functionalities. 我已经尝试了很多东西来调试这个应用程序,但我认为我还没有完全理解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" } } 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 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;?>

You have lot's of problems with your data. 您的数据存在很多问题。 First of all your should not be saving items as json. 首先,你不应该将项目保存为json。 Or at the very least you should not be saving the item id inside the json object. 或者至少你不应该在json对象中保存item id。 Then you would be able to make use of the time honoured INNER JOIN to get all your products very easily, with minimal code and very fast. 然后,您将能够利用久负盛名的INNER JOIN轻松获得所有产品,并且代码最少且速度非常快。

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

As a side note, you should be using prepared statements instead of string concat for your query. 作为旁注,您应该使用预准备语句而不是字符串concat来进行查询。

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

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