Преглед изворни кода

fixing cart update function

Medowar пре 2 месеци
родитељ
комит
483bcf4c19
1 измењених фајлова са 17 додато и 16 уклоњено
  1. 17 16
      cart.php

+ 17 - 16
cart.php

@@ -8,24 +8,25 @@ $pageTitle = 'Warenkorb';
 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     if (isset($_POST['update_cart'])) {
         $quantities = $_POST['quantities'] ?? [];
-        foreach ($quantities as $productId => $quantity) {
-            $quantity = (int)$quantity;
-            if ($quantity <= 0) {
-                // Remove from cart
-                $_SESSION['cart'] = array_filter($_SESSION['cart'], function($item) use ($productId) {
-                    return $item['product_id'] != $productId;
-                });
-                $_SESSION['cart'] = array_values($_SESSION['cart']); // Re-index
-            } else {
-                // Update quantity
-                foreach ($_SESSION['cart'] as &$item) {
-                    if ($item['product_id'] == $productId) {
-                        $item['quantity'] = $quantity;
-                        break;
-                    }
+        $newCart = [];
+
+        foreach ($_SESSION['cart'] as $index => $item) {
+            $newQty = isset($quantities[$index]) ? (int)$quantities[$index] : $item['quantity'];
+
+            if ($newQty > 0) {
+                $newItem = [
+                    'product_id' => $item['product_id'],
+                    'quantity' => $newQty
+                ];
+                if (isset($item['size']) && $item['size'] !== '') {
+                    $newItem['size'] = $item['size'];
                 }
+                $newCart[] = $newItem;
             }
+            // If newQty <= 0, item is removed from cart
         }
+
+        $_SESSION['cart'] = $newCart;
     } elseif (isset($_POST['remove_item'])) {
         $productId = (int)$_POST['product_id'];
         $size = isset($_POST['size']) ? sanitize($_POST['size']) : null;
@@ -99,7 +100,7 @@ include __DIR__ . '/includes/header.php';
                 <div class="cart-item-actions">
                     <label>
                         Menge:
-                        <input type="number" name="quantities[<?php echo $cartItem['product']['id']; ?>]" 
+                        <input type="number" name="quantities[<?php echo $cartItem['cart_index']; ?>]" 
                                value="<?php echo $cartItem['quantity']; ?>" 
                                min="0" 
                                max="<?php echo $itemStock; ?>"