Skip to Content
Course content

62: Practice Exercise: Building a Session-Based Shopping Cart

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of a session-based shopping cart like a waiter with a notepad at a restaurant. The waiter doesn't memorize every single request from every table in the room—that's a recipe for disaster. Instead, they carry a small pad of paper. When you tell them you want a burger, they scribble it down. When you decide you also want a side of fries, they add it to the list on that same piece of paper. The notepad stays with your table until you pay the bill and leave. If the waiter forgets who you are, the notepad is what tells them exactly what you've ordered so far.

In PHP, the $_SESSION superglobal is that notepad. The server is the waiter, and the session ID (stored in a cookie on the user's browser) is the table number. Without the session, PHP is "stateless," meaning it forgets who the user is the second the page finishes loading. By using $_SESSION, we can "scribble down" product IDs and quantities and have them still be there when the user navigates to the checkout page.

The Mental Model for Cart Data

I've seen a lot of beginners try to store the entire product object—name, price, description—directly in the session. Don't do that. It's a bad habit. If you change a product's price in your database, but the user has the old price saved in their session, you're going to have a headache. Instead, only store the Product ID and the Quantity.

I prefer using the product ID as the key in an associative array. It makes updating quantities a breeze. Here is how I'd structure the session data:

$_SESSION['cart'] = [
    'prod_123' => 2, // 2 units of product 123
    'prod_456' => 1  // 1 unit of product 456
];

Handling the 'Add to Cart' Logic

When a user clicks "Add to Cart," you aren't just adding a row to a list; you're checking if that item already exists in the "notepad." If it does, you just bump the number up. If it doesn't, you create the entry.

Here is a clean way to handle this logic. I'm assuming you're getting the product ID from a $_POST request:

session_start();

$productId = $_POST['product_id'];

// If the cart doesn't exist yet, initialize it as an empty array
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// If the item is already in the cart, increment the quantity.
// Otherwise, set it to 1.
if (isset($_SESSION['cart'][$productId])) {
    $_SESSION['cart'][$productId]++;
} else {
    $_SESSION['cart'][$productId] = 1;
}

Tallying the Bill

Since we only stored the IDs and quantities, the "Checkout" page needs to do some heavy lifting. You'll need to loop through your session array, fetch the current price for each ID from your database (or a mock product array), and multiply it by the quantity.

I usually write a helper function for this to keep the HTML clean. Something like this:

function calculateTotal($cart, $productCatalog) {
    $total = 0;
    foreach ($cart as $id => $quantity) {
        if (isset($productCatalog[$id])) {
            $total += $productCatalog[$id]['price'] * $quantity;
        }
    }
    return $total;
}

One quick tip: always remember to call session_start() at the very top of every single file that touches the cart. If you forget, your notepad disappears, and your users will be very confused why their cart keeps emptying itself.




📋 Practical Task

Exercise: The Vintage Vinyl Store Cart

Your goal is to build a functional prototype of a shopping cart for a record store. You don't need a database for this; a hard-coded associative array acting as your "catalog" will work perfectly.

  • The Catalog: Create an array called $products where the keys are IDs (e.g., 'vinyl_01') and the values are arrays containing 'name' and 'price'.
  • The Storefront: Create a page that lists these records with an "Add to Cart" button for each. This should send the ID via a POST request to a processing script.
  • The Cart Logic: Implement the session logic we discussed. If a user adds the same record twice, the quantity in $_SESSION['cart'] should increase.
  • The Review Page: Create a cart.php page that:
    • Displays the name of each item in the cart.
    • Displays the quantity of each item.
    • Calculates and displays the subtotal for each line item and the final grand total for the whole order.
  • The Clear Action: Add a "Empty Cart" button that uses unset($_SESSION['cart']) to wipe the notepad clean.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.