2016-02-03 57 views
0

我知道如何更改購物車數組中的數量,但是我正在使用獲取該物料的詳細信息,並且看起來像刷新時發生的,它不再具有該物料的ID而是返回這些錯誤。PHP更改購物車數組中的數量

有沒有辦法在不刷新的情況下加載新的金額?

WAMP Screenshot

這裏是我的量增減部分:

<?php 
//section 3 
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") { 
    // execute some code 
    $item_to_adjust = $_POST['item_to_adjust']; 
    $quantity = $_POST['quantity']; 
    $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers 
    if ($quantity >= 100) { $quantity = 99; } 
    if ($quantity < 1) { $quantity = 1; } 
    if ($quantity == "") { $quantity = 1; } 
    $i = 0; 
    foreach ($_SESSION["cart_array"] as $each_item) { 
     $i++; 
     while (list($key, $value) = each($each_item)) { 
      if ($key == "item_id" && $value == $item_to_adjust) { 
       // That item is in cart already so let's adjust its quantity using array_splice() 
       array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity))); 
      } // close if condition 
     } // close while loop 
    } // close foreach loop 
} 
?> 

這裏是GET部分:

<?php 
//render cart 
$cartOutput = ""; 
$cartTotal =""; 
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) <1){ 
    $cartOutput = "<h2 align=center'>Your shopping cart is empty</h2>"; 

}else{ 
    $i = 0; 
    foreach($_SESSION["cart_array"] as $each_item){ 

     $item_id = $each_item['item_id']; 

     include_once('config/database.php'); 
     include_once('object/chair.php'); 
     $database = new Database(); 
     $conn = $database->getConnection(); 
     $chair = new Chair($conn); 
     $chair->id = $each_item['details_id']; 
     $stmt = $chair->readDetails();  
     while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
      $product_name = $row['chair_name']; 
      $price = $row['PRICE']; 
     } 

     $pricetotal = $price * $each_item['quantity']; 
     $cartTotal = $pricetotal + $cartTotal; 
     setlocale(LC_MONETARY, "en_US"); 
     $pricetotal = number_format($pricetotal, 2, '.', '\''); 
     $cartOutput .="<tr>"; 
     $cartOutput .= "<td>".$product_name."</td>"; 
     $cartOutput .= "<td>$".$price."</td>"; 

     $cartOutput .= '<td><form action="cart.php" method="post"> 
<input name="quantity" type="text" value="'.$each_item['quantity'].'" size="1" maxlength="2" /> 
     <input name="adjustBtn' . $item_id . '" type="submit" value="change" /> 
     <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> 
     </form></td>'; 

     // $cartOutput .= "<td>".$each_item['quantity']."</td>"; 
     $cartOutput .= "<td>$".$pricetotal."</td>"; 
     $cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; 
     $cartOutput .="</tr>"; 
     $i++; 

回答

0

添加GET來後緩解沒有變種的錯誤但是它會將項目的信息更改爲第一項,並且不會僅與一個項目配合使用