October 1, 2020
Hot Topics:

Developing a Ajax-driven Shopping Cart with PHP and Prototype

  • By Jason Gilmore
  • Send Email »
  • More Articles »

In recent weeks I've been working on an e-commerce project. Among the project goals included building an Ajax-driven shopping cart which is intended to further enhance the user's shopping experience. In the latest installment of this ongoing PHP series, I'll show you how to build a shopping cart using PHP, session handling, and the Prototype JavaScript library (introduced in an earlier installment). The cart allows users to add and delete products from the cart, as well as change cart quantities. And of course, the interaction is seemingly instantaneous, allowing for the user to continue shopping without waiting for the page to reload.

A Sample Products Table

Although we won't integrate a database into the cart mechanism, as a matter of reference a simple products table might look like this:

CREATE TABLE products (
   title VARCHAR(50) NOT NULL,
   author VARCHAR(50) NOT NULL,
   price DECIMAL(4,2) NOT NULL,

Next let's add a few table rows:

INSERT INTO products VALUES(NULL,"Beginning PHP and MySQL 5, 2E",
    "W. Jason Gilmore", "44.99");
INSERT INTO products VALUES(NULL,"Beginning Ubuntu Linux ",
    "Keir Thomas", "39.99");
    "Jay Pipes and Michael Kruckenberg", "49.99");

Creating the Shopping Cart

The easiest way to manage user shopping carts is through an array stored in a user session. This key represents the product id, and the value represents the count of that particular item found in the cart. Therefore if the user's shopping cart consisted of two copies of "Beginning PHP and MySQL 5", and 3 copies of "Pro MySQL", the array would look like this:

$cart[1] = 2;
$cart[3] = 3;

To manage this array, I've created a class called Shopping_Cart. This class contains two simple methods for adding to and subtracting from the shopping cart:

class Shopping_Cart {

    private $cart;

    function __construct($cart="") {
        $this->cart = $cart;

    function getCart() {
        return $this->cart;
    function addToCart($item) {
        if(isset($this->cart[$item])) {
        } else {
            $this->cart[$item] = 1;

    function deleteFromCart($item) {
        if(isset($this->cart[$item])) {
            if($this->cart[$item] == 0) {

Using this class, adding products to and subtracting them from the cart is a breeze. Take a moment to work through the following sample behavior:

$cart = new Shopping_Cart();

// Add a copy of "Beginning PHP and MySQL 5, Second Edition"

// Add two copies of "Pro MySQL"

// Output cart

// Delete item from cart

// Output cart again

The resulting output follows:

Array ( [1] => 1 [3] => 2)
Array ( [3] => 2 )

With the shopping cart working as expected, it's time to move on to how we're going to bind the shopping cart to the user as he navigates the website. This is accomplished using PHP sessions.

Binding the Shopping Cart to the User

Chances are your web site's product catalog will be spread across several pages. In order to accommodate the user's desire to manage his shopping cart as he navigates the website, the shopping cart will need to travel with him from one page to the next. Binding such data to a specific user is generally done using a feature known as sessions, which typically involves assigning the user a unique identifier which is stored in a cookie, and then mapping that identifier to his shopping cart contents which reside on the server. Resultingly, with each page request the shopping cart contents can be easily retrieved and displayed to the page, or be manipulated anew before being saved back to the session.

Let's revise the above code to initiate a session, add a few products to the shopping cart, and save the cart to a session. The script concludes with a link to another page, which outputs the session contents to prove the cart did indeed travel with the user's movements:


   $cart = new Shopping_Cart();

   // Add a copy of "Beginning PHP and MySQL 5, Second Edition"

   // Add two copies of "Pro MySQL"

   // Dump cart contents to array
   $items = $cart->getCart();

   // Assign array to session
   $_SESSION["cart"] = $items;

<a href="nextpage.php">Go to the next page</a>

The nextpage.php script follows:


Executing this script produces the following output:

Array ( [1] => 1 [3] => 2 )

At this point, you understand how both the shopping cart and sessions work together. Next let's build a catalog page and integrate the Ajax.

Page 1 of 2

This article was originally published on January 25, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date