Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 43

PHP Shopping Cart using Sessions

In this lesson: Build a shopping cart in PHP using sessions — add, update quantity, remove and total price — complete source code.

What we are building

A shopping cart remembers what a user wants to buy as they browse. We will build a simple cart using the session, so it survives across pages without a database until checkout. It will add items, update quantities, show the total, and remove items.

💡 The cart lives in $_SESSION["cart"] as an array keyed by product id, each holding a quantity.

Starting the cart

<?php
  session_start();
  if (!isset($_SESSION["cart"])) {
      $_SESSION["cart"] = [];   // empty cart
  }
?>

We start the session and make sure the cart array exists. Every cart page begins like this so the cart is always ready to use.

Add to cart

<?php
  $id = (int)$_GET["id"];   // product id

  if (isset($_SESSION["cart"][$id])) {
      $_SESSION["cart"][$id] += 1;   // already there: +1
  } else {
      $_SESSION["cart"][$id] = 1;    // new item
  }
  echo "Added to cart";
?>
Added to cart

If the product is already in the cart, we increase its quantity; otherwise we add it with quantity 1. Using the id as the key keeps one entry per product.

View the cart and total

<?php
  // pretend prices come from the database:
  $prices = [1 => 100, 2 => 250, 3 => 90];

  $total = 0;
  foreach ($_SESSION["cart"] as $id => $qty) {
      $line = $prices[$id] * $qty;
      $total += $line;
      echo "Product $id x $qty = $line\n";
  }
  echo "Total: $total";
?>
Product 1 x 2 = 200
Total: 200

We loop the cart, look up each price from a trusted source, multiply by quantity, and add to the total. Never trust a price sent from the browser.

Remove an item

<?php
  $id = (int)$_GET["id"];
  unset($_SESSION["cart"][$id]);   // remove that product
  echo "Removed from cart";
?>
Removed from cart

unset deletes that product from the cart array. To empty the whole cart, set $_SESSION["cart"] = [].

Common mistakes

  • Trusting prices from the form. Always fetch the real price from the database by id.
  • Not casting the id. Cast $_GET["id"] to (int) for safety.
  • Duplicate entries. Key the cart by product id and increase quantity instead of adding again.
  • Forgetting session_start(). Every cart page needs it to read the cart.

Summary

  • A shopping cart lives in the session while the user browses.
  • Store it as an array keyed by product id, each holding a quantity.
  • Adding an existing product increases its quantity.
  • Calculate the total from trusted database prices, not the browser.
  • Use unset to remove an item; clear the array to empty the cart.

Next, save the final order with PHP CRUD, or manage the session in sessions and cookies.

Frequently Asked Questions

Where should a shopping cart be stored?
For most sites, the cart lives in the session while the user shops. The session keeps the cart on the server across pages. When the user checks out, you save the order to the database.
How do I structure the cart in the session?
A common way is an associative array keyed by product id, where each value holds the quantity (and optionally name and price). This makes it easy to add, update the quantity, or remove by id.
How do I add the same product twice?
Check if the product id already exists in the cart. If it does, increase its quantity; if not, add it with quantity 1. This avoids duplicate entries for the same product.
How do I calculate the cart total?
Loop through the cart items, multiply each item's price by its quantity, and add them up. Keep the price from a trusted source (your database), not from the browser, so users cannot change it.
Why not store prices from the form?
A user could change a hidden price field in the browser. Always look up the real price from your database using the product id, so the total cannot be tampered with.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicExport to CSV/Excel Your progress: 43 / 50 (86%) · Lesson 44 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free