简体   繁体   中英

updating shopping cart quantity (partially works)

I have a shopping cart which at the moment allows me to add products, remove products and with 1 product in the cart I can change its quantity.

However if i have 2 products in the cart and I try to change the quantity of the first item the site crashes. It doesnt reload the page with the new quantity it just times out and you can no longer click on any other links on the website.

The code to display the quantity is:

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

and the code which deals with this is here:

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"] 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"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}
?>

been looking through answers on here but cant see a solution. Can anyone help me with this? I will try and provide any other information that may be needed to help.

just to clarify, the cart works perfectly until I try to change the quantity of an item that isnt the last item I added. So if I have 3 items in the cart I cant change the quantity of item 1 or 2 but I can change item 3

Thanks in advance

The solution is to use a copy of the cart array for editing.

Editing the array which is currently being iterated can cause unexpected behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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