2016-12-03 88 views
-1

我試圖循環表名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

回答

0

這是問題之一。你告訴我你的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。