What are some simple ways to implement a shopping cart system in PHP for a website?
Implementing a shopping cart system in PHP for a website involves creating a session to store the cart items, adding products to the cart, updating quantities, and removing items. One simple way to achieve this is by using an array to store the cart items in the session.
// Start the session
session_start();
// Add a product to the cart
if(isset($_POST['product_id'])) {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
// Check if the product is already in the cart
if(isset($_SESSION['cart'][$product_id])) {
// Update the quantity
$_SESSION['cart'][$product_id] += $quantity;
} else {
// Add the product to the cart
$_SESSION['cart'][$product_id] = $quantity;
}
}
// Remove a product from the cart
if(isset($_GET['remove'])) {
$product_id = $_GET['remove'];
unset($_SESSION['cart'][$product_id]);
}
// Display the cart items
if(isset($_SESSION['cart'])) {
foreach($_SESSION['cart'] as $product_id => $quantity) {
echo "Product ID: $product_id, Quantity: $quantity <br>";
}
}