Professional shopping cart systems should be built with clean, maintainable code. Consider using an with a dedicated Cart class:
Write robust tests for your ShoppingCart class checking behaviors such as adding negative quantities, handling zero-stock items, and boundaries for extreme integers.
<?php // Validate product ID $productId = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); if (!$productId || $productId <= 0) die(json_encode(['error' => 'Invalid product ID'])); addcartphp num high quality
Uses filter_input to force strict integer typing on product IDs and quantities.
Allows items to be added without page reloads. 2. Setting Up the Database Structure Professional shopping cart systems should be built with
A high-quality PHP shopping cart script does more than just move items from a product page to a checkout—it manages sessions, secures transactions, and scales with your business. Essential Features of High-Quality PHP Cart Scripts
Total calculation must be accurate and efficient. Rather than storing product prices in the session (which can become outdated if prices change), a high-quality system recalculates totals using current database values. Allows items to be added without page reloads
class Cart private $pdo;
// Validate product exists and has sufficient stock // ... proceed
PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]); catch (PDOException $e) echo json_encode(['success' => false, 'message' => 'Database connection failed.']); exit; // 2. Validate Request Method if ($_SERVER['REQUEST_METHOD'] !== 'POST') http_response_code(405); echo json_encode(['success' => false, 'message' => 'Method Not Allowed. Use POST.']); exit; // 3. Sanitize and Validate Input Parameters (ID and Num) $productId = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $quantity = filter_input(INPUT_POST, 'num', FILTER_VALIDATE_INT); if ($productId === false || $productId === null || $quantity === false || $quantity === null) http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid product ID or quantity format.']); exit; if ($quantity <= 0) http_response_code(400); echo json_encode(['success' => false, 'message' => 'Quantity must be greater than zero.']); exit; // 4. Verify Product Existence and Stock Levels $stmt = $pdo->prepare("SELECT id, name, price, stock FROM products WHERE id = :id LIMIT 1"); $stmt->execute(['id' => $productId]); $product = $stmt->fetch(); if (!$product) http_response_code(404); echo json_encode(['success' => false, 'message' => 'Product not found.']); exit; // Initialize the cart session structure if it doesn't exist if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // Calculate target quantity if item already exists in cart $currentCartQty = isset($_SESSION['cart'][$productId]) ? $_SESSION['cart'][$productId]['num'] : 0; $targetQty = $currentCartQty + $quantity; // Inventory Check if ($targetQty > $product['stock']) http_response_code(400); echo json_encode([ 'success' => false, 'message' => "Cannot add requested quantity. Only $product['stock'] items available in stock." ]); exit; // 5. Update Cart State $_SESSION['cart'][$productId] = [ 'id' => (int)$product['id'], 'name' => $product['name'], 'price' => (float)$product['price'], 'num' => (int)$targetQty ]; // Calculate total cart items for UI updates $totalItems = 0; foreach ($_SESSION['cart'] as $item) $totalItems += $item['num']; // 6. Return High-Quality JSON Response echo json_encode([ 'success' => true, 'message' => 'Product added to cart successfully.', 'cart_count' => $totalItems, 'item' => $_SESSION['cart'][$productId] ]); Use code with caution. Deep Dive into High-Quality Optimization Techniques 1. Why FILTER_VALIDATE_INT Matters