add-cart.php (Complete Feature)
<?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;
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; //
// 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!";
// Redirect back to previous page or product page $redirect = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'products.php'; header("Location: $redirect"); exit; ?>
2. For product ID + quantity
// Expected format: "123:2"
$num = $_GET['num'] ?? '';
if (!preg_match('/^(\d+):(\d+)$/', $num, $matches))
die('Invalid format. Use ID:QTY');
$productId = (int)$matches[1];
$quantity = (int)$matches[2];
if ($quantity < 1 || $quantity > 50)
die('Quantity out of range');
// Verify product exists and is in stock
Step 3 – Check Product Availability
Query database for product stock, status, price.
SELECT stock, price, status FROM products WHERE id = ?
If stock < requested quantity, cap quantity or show error.
Enhanced Version with AJAX Support
<?php session_start();// Initialize cart if (!isset($_SESSION['cart'])) $_SESSION['cart'] = [];
// Function to get product details (example) function getProductDetails($product_id) // Replace with your database query $products = [ 1 => ['name' => 'Product 1', 'price' => 29.99, 'stock' => 50], 2 => ['name' => 'Product 2', 'price' => 49.99, 'stock' => 30], 3 => ['name' => 'Product 3', 'price' => 19.99, 'stock' => 100], ]; return isset($products[$product_id]) ? $products[$product_id] : null;
// Get request parameters $product_id = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0; $quantity = isset($_REQUEST['num']) ? (int)$_REQUEST['num'] : 1; $response_type = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ? 'json' : 'html';
// Validate product if ($product_id <= 0) if ($response_type == 'json') echo json_encode(['success' => false, 'error' => 'Invalid product ID']); exit; header('Location: products.php?error=invalid_product'); exit;
// Validate quantity if ($quantity <= 0) $quantity = 1;
// Check stock availability (optional) $product = getProductDetails($product_id); if ($product && $quantity > $product['stock']) if ($response_type == 'json') echo json_encode(['success' => false, 'error' => 'Insufficient stock']); exit; header('Location: products.php?error=insufficient_stock'); exit;
// Update cart if (isset($_SESSION['cart'][$product_id])) $new_quantity = $_SESSION['cart'][$product_id] + $quantity;
// Check stock for new total if ($product && $new_quantity > $product['stock']) if ($response_type == 'json') echo json_encode(['success' => false, 'error' => 'Would exceed stock limit']); exit; header('Location: products.php?error=stock_limit_exceeded'); exit; $_SESSION['cart'][$product_id] = $new_quantity;else $_SESSION['cart'][$product_id] = $quantity;
// Calculate cart totals $cart_count = array_sum($_SESSION['cart']); $cart_total = 0; foreach ($_SESSION['cart'] as $id => $qty) $prod = getProductDetails($id); if ($prod) $cart_total += $prod['price'] * $qty;
// Return response if ($response_type == 'json') echo json_encode([ 'success' => true, 'message' => 'Product added to cart', 'cart_count' => $cart_count, 'cart_total' => number_format($cart_total, 2), 'product_id' => $product_id, 'quantity_added' => $quantity, 'new_quantity' => $_SESSION['cart'][$product_id] ]); exit;
// HTML response - redirect $_SESSION['cart_message'] = "Product added to cart successfully!"; $redirect = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'products.php'; header("Location: $redirect"); exit; ?>
2. Server-Side Price Calculation
Never accept price information from the client. The add-cart.php script should only receive the item_id and the quantity. The script should then query the database to retrieve the actual price of the item.
$item_id = intval($_GET['item_id']);
$quantity = intval($_GET['num']);
// Fetch price from DB
$stmt = $pdo->prepare("SELECT price FROM products WHERE id = ?");
$stmt->execute([$item_id]);
$product = $stmt->fetch();
if ($product && $quantity > 0)
$unit_price = $product['price'];
// Add to cart logic using the trusted database price
Principle 3: Use Prepared Statements
$stmt = $conn->prepare("SELECT price, stock FROM products WHERE id = ? AND active = 1");
$stmt->bind_param("i", $product_id);
$stmt->execute();