对于每个循环不循环所有行

问题描述:

我试图循环表名cart的所有行,但foreach只显示最后一行输入并始终忽略以前的行。假设我在cart_table中有5个产品,那么只会显示product_id[5]。如果用户添加第六个项目,则现在仅显示product_id[6]$item_count也总是等于1,好像只有一个项目有多个时。根据我的理解,foreach($items as $item)$items即使有多个项目也不会被视为数组。当我var_dump($items);它显示array(1) { [0]=>...对于每个循环不循环所有行

add_cart.php

<?php 
ob_start(); 
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php'; 
$product_id = isset($_POST['product_id'])? sanitize($_POST['product_id']):''; 
$size = isset($_POST['size'])? sanitize($_POST['size']):''; 
$available = isset($_POST['available'])? sanitize($_POST['available']):''; 
$quantity = isset($_POST['quantity'])? sanitize($_POST['quantity']):''; 
$item = array(); 
$item[] = array(
    'id'   => $product_id, 
    'size'   => $size, 
    'quantity' => $quantity, 
    'available' => $available 
    ); 
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false; 
$query = $db->query("SELECT * FROM product WHERE id = '{$product_id}'"); 
$product = mysqli_fetch_assoc($query); 
$_SESSION['success_flash'] = $product['prod_name']. ' was added to your cart.'; 

//check if the cart cookie exists 
if (is_array($cart_id != ' ')) { 
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'"); 
$cart = mysqli_fetch_assoc($cartQ); 
$previous_items = json_decode($cart['items'],true); 
$item_match = 0; 
$new_items = array(); 

foreach($previous_items as $pitem){ 
    if ($item[0]['id'] == $pitem['id'] && $item[0]['size'] == $pitem['size']) { 
     $pitem['quantity'] = $pitem['quantity'] + $item[0]['quantity']; 

if ($pitem['quantity'] > $available) { 
    $pitem['quantity'] = $available; 

} 
$item_match = 1; 
} 
$new_items[] = $pitem; 
} 

if ($item_match != 1) { 
    $new_items = array_merge($item,$previous_items); 
} 

$items_json = json_encode($new_items); 
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days")); 
$db->query("UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = '{cart_id}'"); 
setcookie(CART_COOKIE,'',1,"/",$domain,false); 
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false); 

}else{ 
// add to databse and set cookie 
    $items_json = json_encode($item); 
    $cart_expire = date("Y-m-d H:i:s",strtotime("+30 days")); 
    $db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')"); 
    $cart_id = $db->insert_id; 
    setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false); 
} 
?> 

cart.php

<?php 
require_once 'core/init.php'; 
//include 'includes/headerpartial.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 if($cart_id == ' '): ?> 
    <div class="bg-danger"> 
     <p class='text-center text-danger'>Your cart is empty.</p> 
    </div> 
<?php else: ?> 
    <?php 
    foreach ($items as $item) { 
     var_export($items); 
     $product_id = $item['id']; 
     $productQuery = $db->query("SELECT * FROM product WHERE id ='{$product_id}' "); 
     $product  = mysqli_fetch_assoc($productQuery); 
     $sArray  = explode(',', $product['sizes']); 

/*  foreach ($sArray as $sizeString) { 
      $s = explode(':', $sizeString); 
      if($s[0] == $item['size']) { 
       $available = $s[1]; 
      } 
     }*/ 

     ?> 

     <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="remove"> 
       <div>&times</div> 
      </td> 
     </tr> 
     <?php 
     $i ++; 
     $item_count += $item['quantity']; 
     $sub_total += ($product['price'] * $item['quantity']); 

    } 
    $tax   = TAXRATE * $sub_total; 
    $tax   = number_format($tax, 2); 
    $grand_total = $tax + $sub_total; 

    <?php  endif;?> 
+0

你能显示整个代码吗?在快速浏览了您所展示的内容之后,问题可能来自之前的代码。 –

+0

你在说哪个foreach?孩子或父母? – McStuffins

+1

“显示”代码的最后一行需要是endif; ?>因为你缺少一个endif:如果这是代码实际上在if语句内结束的地方。 – TimBrownlaw

这是问题之一。你告诉我你的id是一个自动增量int,所以我想提出这个答案。问题出在你的sql命令中。

UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = {cart_id} 

请务必将该命令放在引号中。另外,我强烈建议使用以下命令来准备JSON:

$itemJson = addslashes($itemJson); 

然后,您可以运行该命令。另一种可能性是使用mysqli的prepare方法。这里是一个链接到一些例子:

w3schools.com

,如果你有任何问题,请随时更新你的问题,但一定要在评论@McStuffins。