To ensure the code is maintainable and reusable, we separate the logic into two core classes: Product and ShoppingCart . Using PHP 8+ features like constructor property promotion makes this code concise and highly readable. 1. The Product Class
-- Products Table CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, price DECIMAL(10, 2) NOT NULL, stock_quantity INT NOT NULL ); -- Cart Table (Persistent for logged-in users) CREATE TABLE cart ( id INT AUTO_INCREMENT PRIMARY KEY, session_id VARCHAR(255) NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL, FOREIGN KEY (product_id) REFERENCES products(id) ); Use code with caution. 3. Implementing the "AddCartPHP" Logic (Backend) The core logic must handle three scenarios: Product not in cart: Create new row. Product already in cart: Update quantity. Stock check: Ensure requested num is available. High-Quality add_to_cart.php Example
foreach ($_SESSION['cart'] as $item) $product = $products[$item['product_id']] ?? null; if ($product) $total += (float)$product['price'] * (int)$item['quantity']; addcartphp num high quality
CREATE TABLE cart_items ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL CHECK (quantity > 0), added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY (user_id, product_id) );
When multiple users or requests modify the same cart, a high-quality system uses: To ensure the code is maintainable and reusable,
In this comprehensive guide, we’ll dissect what it takes to write a feature in PHP. You’ll learn how to manage item quantities correctly, avoid common pitfalls (injection, session abuse, quantity tampering), and produce code that is secure, maintainable, and user‑friendly.
false, 'message' => 'Method Not Allowed']); exit; // 2. Retrieve and sanitize input parameters $product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT); $quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT); if ($product_id === false || $product_id === null || $quantity === false || $quantity === null) http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid product ID or quantity.']); exit; if ($quantity < 1) http_response_code(400); echo json_encode(['success' => false, 'message' => 'Quantity must be at least 1.']); exit; try // 3. Verify product existence and stock level via Prepared Statements $stmt = $pdo->prepare("SELECT id, name, price, stock FROM products WHERE id = :id AND status = 'active' LIMIT 1"); $stmt->execute(['id' => $product_id]); $product = $stmt->fetch(PDO::FETCH_ASSOC); if (!$product) http_response_code(404); echo json_encode(['success' => false, 'message' => 'Product not found or unavailable.']); exit; // 4. Calculate current total requested quantity $current_cart_qty = isset($_SESSION['cart'][$product_id]) ? $_SESSION['cart'][$product_id] : 0; $total_requested_qty = $current_cart_qty + $quantity; // 5. Enforce inventory limits if ($total_requested_qty > $product['stock']) http_response_code(400); echo json_encode([ 'success' => false, 'message' => "Cannot add items. Only $product['stock'] units available in stock." ]); exit; // 6. Update session cart state if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; $_SESSION['cart'][$product_id] = $total_requested_qty; // 7. Calculate cart summary metrics $total_items = array_sum($_SESSION['cart']); echo json_encode([ 'success' => true, 'message' => 'Item successfully added to cart.', 'total_items' => $total_items ]); exit; catch (PDOException $e) // Log error internally; do not expose raw system errors to users error_log("Database error in add_to_cart.php: " Use code with caution. High-Quality Implementation Best Practices 1. Preventing Security Vulnerabilities The Product Class -- Products Table CREATE TABLE
$this->saveCart(); return true;
A high-quality cart system relies on a relational database (like MySQL) to validate inventory and a secure session handler to store user choices.
To ensure the data coming into your PHP backend is high quality from the start, use strict HTML attributes: