Add-cart.php Num «99% Premium»
<?php session_start();// Initialize cart if not exists if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
// Get product ID and quantity from request $product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0; $quantity = isset($_GET['num']) ? (int)$_GET['num'] : 1;
// Validate inputs if ($product_id <= 0) header('Location: products.php?error=invalid_product'); exit; add-cart.php num
if ($quantity <= 0) $quantity = 1;
// Optional: Fetch product details from database to validate // $product = getProductById($product_id); // if (!$product) // header('Location: products.php?error=product_not_found'); // exit; // // Get product ID and quantity from request
// Add to cart logic if (isset($_SESSION['cart'][$product_id])) // Product exists, update quantity $_SESSION['cart'][$product_id] += $quantity; else // New product, add to cart $_SESSION['cart'][$product_id] = $quantity;
// Optional: Set success message $_SESSION['cart_message'] = "Product added to cart successfully!"; if ($quantity <= 0) $quantity = 1;
// Redirect back to previous page or product page $redirect = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'products.php'; header("Location: $redirect"); exit; ?>
INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity);
Before writing code, it is essential to understand what add-cart.php actually needs to do. It is not simply "saving an item." The script must:
![Официальный ремонт техники [brandname] в [cityname]](https://servis-toshiba.ru/wp-content/uploads/2025/07/ofitsialnyj-remont-tehniki-toshiba.jpg)