Building a Basic E-commerce Cart in PHP

Table of Contents

  • Introduction to Building an E-commerce Cart
  • Key Features of the E-commerce Cart
  • Setting Up the Database for E-commerce
  • Creating the Cart Model and Database Operations
  • Building the Cart Pages
  • Adding Products to the Cart
  • Displaying the Cart Contents
  • Handling Cart Updates and Deletions
  • Conclusion

Introduction to Building an E-commerce Cart

Building an e-commerce cart is a fundamental project for learning PHP and web development. It simulates a real-world shopping cart experience where users can add products, view the cart contents, and make changes before proceeding to checkout. In this module, we will build a simple e-commerce cart system using PHP and MySQL, which will be functional enough for testing various e-commerce features.

By the end of this module, you will have a basic e-commerce cart where users can add products, view their cart, and modify their selections.


Key Features of the E-commerce Cart

For this simple e-commerce cart, the following features will be included:

  1. Product Display: A page showing available products that users can add to their cart.
  2. Add Products to Cart: The ability to add products to a shopping cart.
  3. View Cart: A page to view the items currently in the cart.
  4. Update Cart: Users can update quantities or remove items from the cart.
  5. Session-based Cart: The cart will be session-based, so it will persist throughout the user’s visit to the website.

Setting Up the Database for E-commerce

For our basic e-commerce cart system, we will need two tables:

  1. Products: To store product information.
  2. Cart: To store the items added to the shopping cart.

Here is the SQL to create the products and cart tables:

-- Table for storing product information
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
image VARCHAR(255) NOT NULL
);

-- Table for storing cart items (this table is for the session cart, not a permanent database table)
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT,
session_id VARCHAR(255),
FOREIGN KEY (product_id) REFERENCES products(id)
);

The products table stores information about each product, including its name, description, price, and image. The cart table stores the items added to the cart, with a reference to the products table and a quantity field. The session_id will ensure that the cart is unique to each user.


Creating the Cart Model and Database Operations

We will create a CartModel class to handle operations related to the shopping cart, such as adding products, retrieving the cart, updating quantities, and removing items.

Database Connection

We’ll use the same db.php file for database connections as in the previous modules.

<?php
// db.php
$host = 'localhost';
$dbname = 'ecommerce_system';
$username = 'root';
$password = '';

try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>

Cart Model

Now let’s create the CartModel.php class to handle the cart operations:

<?php
require_once 'db.php';

class CartModel {

// Add a product to the cart
public function addToCart($productId, $quantity) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "SELECT * FROM cart WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $sessionId]);
$cartItem = $stmt->fetch(PDO::FETCH_ASSOC);

if ($cartItem) {
// If product already exists in the cart, update the quantity
$newQuantity = $cartItem['quantity'] + $quantity;
$sql = "UPDATE cart SET quantity = ? WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$newQuantity, $productId, $sessionId]);
} else {
// Otherwise, insert a new cart item
$sql = "INSERT INTO cart (product_id, quantity, session_id) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $quantity, $sessionId]);
}
}

// Get all items in the cart
public function getCartItems() {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "SELECT * FROM cart WHERE session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sessionId]);
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch product details for each item in the cart
foreach ($cartItems as &$item) {
$sql = "SELECT * FROM products WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$item['product_id']]);
$item['product'] = $stmt->fetch(PDO::FETCH_ASSOC);
}

return $cartItems;
}

// Update quantity of a cart item
public function updateCartItem($productId, $quantity) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "UPDATE cart SET quantity = ? WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$quantity, $productId, $sessionId]);
}

// Remove an item from the cart
public function removeCartItem($productId) {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "DELETE FROM cart WHERE product_id = ? AND session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$productId, $sessionId]);
}

// Clear the entire cart
public function clearCart() {
session_start();
$sessionId = session_id();

global $pdo;
$sql = "DELETE FROM cart WHERE session_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sessionId]);
}
}
?>

The CartModel class provides several methods:

  • addToCart(): Adds a product to the cart or updates the quantity if the product already exists.
  • getCartItems(): Retrieves all items in the cart, including product details.
  • updateCartItem(): Updates the quantity of a product in the cart.
  • removeCartItem(): Removes a product from the cart.
  • clearCart(): Clears all items in the cart.

Building the Cart Pages

Now that the back-end is set up, let’s create the front-end pages for the cart system.

Product Listing Page (products.php)

This page will display all available products that users can add to the cart:

<?php
require_once 'CartModel.php';

$cartModel = new CartModel();

// Fetch products from the database
global $pdo;
$sql = "SELECT * FROM products";
$stmt = $pdo->query($sql);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Listing</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php foreach ($products as $product): ?>
<li>
<img src="<?php echo $product['image']; ?>" alt="<?php echo $product['name']; ?>">
<h3><?php echo $product['name']; ?></h3>
<p><?php echo $product['description']; ?></p>
<p>Price: $<?php echo $product['price']; ?></p>
<form action="add_to_cart.php" method="POST">
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" value="1" min="1">
<button type="submit">Add to Cart</button>
</form>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>

This page displays each product’s name, description, price, and an “Add to Cart” button.


Add to Cart (add_to_cart.php)

This page handles adding products to the cart:

<?php
require_once 'CartModel.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$productId = $_POST['product_id'];
$quantity = $_POST['quantity'];

$cartModel = new CartModel();
$cartModel->addToCart($productId, $quantity);

header('Location: cart.php');
exit();
}
?>

This script receives the product ID and quantity from the form and adds the item to the cart using the addToCart() method.


Displaying the Cart (cart.php)

Finally, let’s create a page where users can view their cart:

<?php
require_once 'CartModel.php';

$cartModel = new CartModel();
$cartItems = $cartModel->getCartItems();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Cart</title>
</head>
<body>
<h1>Your Shopping Cart</h1>
<ul>
<?php foreach ($cartItems as $item): ?>
<li>
<h3><?php echo $item['product']['name']; ?></h3>
<p>Price: $<?php echo $item['product']['price']; ?></p>
<p>Quantity: <?php echo $item['quantity']; ?></p>
<form action="update_cart.php" method="POST">
<input type="hidden" name="product_id" value="<?php echo $item['product']['id']; ?>">
<input type="number" name="quantity" value="<?php echo $item['quantity']; ?>" min="1">
<button type="submit">Update Quantity</button>
</form>
<a href="remove_cart_item.php?id=<?php echo $item['product']['id']; ?>">Remove</a>
</li>
<?php endforeach; ?>
</ul>
<a href="checkout.php">Proceed to Checkout</a>
</body>
</html>

This page displays the products in the cart along with their quantities and allows the user to update or remove items.


Conclusion

In this module, we built a basic e-commerce cart using PHP and MySQL. We created the necessary database tables and implemented the logic to add, update, and remove items from the cart. The cart is session-based, which ensures that it persists across pages during the user’s visit.

This cart system is a great foundation for a more complex e-commerce website. In future modules, you could expand this system by adding features like user authentication, checkout, payment processing, and order history.