This is the most crucial logic block. If a user clicks "Add to Cart" twice for the same product, you generally don't want two separate rows in your database. You want to increase the quantity of the existing row.
There are two ways to handle this:
We will use the efficient MySQL approach: INSERT ... ON DUPLICATE KEY UPDATE. add-cart.php num
Note: For this to work, you need a Unique Index on user_id and product_id combined in your database table.
try // Begin Transaction for data integrity $pdo->beginTransaction();// The Query // This attempts to insert the row. // If the user_id + product_id combo already exists, it updates the quantity instead. $sql = "INSERT INTO cart_items (user_id, product_id, quantity) VALUES (:user_id, :product_id, 1) ON DUPLICATE KEY UPDATE quantity = quantity + 1"; $stmt = $pdo->prepare($sql); // Bind Parameters (Prevents SQL Injection) $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT); $stmt->execute(); // Commit changes $pdo->commit(); // Redirect user back to cart or product page header("Location: cart.php?success=added"); exit(); catch (PDOException $e) // Rollback if error occurs $pdo->rollBack(); error_log("Cart Error: " . $e->getMessage()); header("Location: products.php?error=database_error"); exit();
The num parameter in add-cart.php typically specifies the product quantity (or product ID + quantity) to add to a shopping cart. This is the most crucial logic block
Never trust the num parameter. Sanitize it immediately:
$quantity = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT);
if ($quantity === false || $quantity === null || $quantity < 1)
$quantity = 1; // Default to safe minimum
if ($quantity > 100) // Set a reasonable max per transaction
die("Quantity exceeds maximum allowed.");