214

Creating Simple Shopping Cart with PHP

Shopping Cart is very important part of any online store, it not only lets users to accumulate list of items for final purchase, but also calculates a total amount for the order. Since my last article on PayPal Express Checkout with PHP, I have received few emails from readers asking how to create simple PHP session based shopping cart for the website. So, keeping that in mind, today we will create a simple but working online shopping cart step by step, which can be integrated easily in any website that runs on PHP.

PHP shopping cart

I have created 4 files for our shopping cart:

  1. Config.php (MySql credentials)
  2. Index.php (list of product information from database)
  3. Cart_update.php (Updates cart items and redirects back to products list page)
  4. View_cart.php (Product summery view before the payment)

Products Information

All our products information should be stored in MySql table, lets create a table named “products”, you can insert the products details manually using PhpMyAdmin, OR there’s also a mysql file in downloadable zip, which you can import in database to get the table and the product details.

 
1
2
3
4
5
6
7
8
9
10
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_code` varchar(60) NOT NULL,
  `product_name` varchar(60) NOT NULL,
  `product_desc` tinytext NOT NULL,
  `product_img_name` varchar(60) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_code` (`product_code`)
) AUTO_INCREMENT=1 ;

Once you create the table, you can create a list of products, similar to picture below:
Product Details

Configuration

Main purpose of the config file is to store different information we need for our script. Just enter the MySql details in the configuration file.

 
1
2
3
4
5
6
7
8
<?php
$currency = '$';
$db_username = 'root';
$db_password = '';
$db_name = 'demo';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
?>

Product List (Index.php)

This will be the page where you want to display the list the products you want to sell to buyers. If you have lots of products, it is better to group them in pages using some sort of pagination. And on the right side of the page will be our shopping-cart box, which will keep track of items user going to purchase later.

Since we are working with sessions, we must activate PHP session in our script by including session_start() on top of the code, then we can start writing codes or include file:

 
1
2
3
4
<?php
session_start();
include_once("config.php");
?>

Listing Products from Database

We will basically fetch the records from database and display them on the page. We will also create a HTML form with Add to Cart button. It doesn’t matter how you are planing to display them, the important part here is the HTML form. Notice the hidden input values? each item contains a form with these hidden values, product code and the return URL, which we will send to cart_update.php using POST method.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div class="products">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   
    $results = $mysqli->query("SELECT * FROM products ORDER BY id ASC");
    if ($results) {
        //output results from database
        while($obj = $results->fetch_object())
        {
           
            echo '<div class="product">';
            echo '<form method="post" action="cart_update.php">';
            echo '<div class="product-thumb"><img src="images/'.$obj->product_img_name.'"></div>';
            echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
            echo '<div class="product-desc">'.$obj->product_desc.'</div>';
            echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
            echo '</div>';
            echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
            echo '<input type="hidden" name="type" value="add" />';
            echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
            echo '</form>';
            echo '</div>';
        }
   
}
?>
</div>

Shopping Cart Box

On the right side of the page we will display small shopping cart box to keep track of user items. The main task of the shopping-cart is to look for session variable called $_SESSION[“products”], which holds the collection of user items in an array, and then retrieve and display its content in the box.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
    $total = 0;
    echo '<ol>';
    foreach ($_SESSION["products"] as $cart_itm)
    {
        echo '<li class="cart-itm">';
        echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
        echo '<h3>'.$cart_itm["name"].'</h3>';
        echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
        echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
        echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
        echo '</li>';
        $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
        $total = ($total + $subtotal);
    }
    echo '</ol>';
    echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> <a href="view_cart.php">Check-out!</a></span>';
    echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&return_url='.$current_url.'">Empty Cart</a></span>';
}else{
    echo 'Your Cart is empty';
}
?>
</div>

Updating Cart

The role of the Cart_update.php is to add and remove items in the shopping cart. When user clicks “Add to Cart” button, the form sends some hidden values such as product code and quantity to Cart_update.php using POST method, which we will use to retrieve product info from the database verifying the existence of the product, and then we create or update $_SESSION[“products”] with new array variables. Removing item works similar way, please go though comment lines below, most of the code is self explanatory.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
session_start(); //start session
include_once("config.php"); //include config file

//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
    $return_url = base64_decode($_GET["return_url"]); //return url
    session_destroy();
    header('Location:'.$return_url);
}

//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty    = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url     = base64_decode($_POST["return_url"]); //return url
   
    //limit quantity for single product
    if($product_qty > 10){
        die('<div align="center">This demo does not allowed more than 10 quantity!<br /><a href="http://sanwebe.com/assets/paypal-shopping-cart-integration/">Back To Products</a>.</div>');
    }

    //MySqli query - get details of item from db using product code
    $results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
    $obj = $results->fetch_object();
   
    if ($results) { //we have the product info
       
        //prepare array for the session variable
        $new_product = array(array('name'=>$obj->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));
       
        if(isset($_SESSION["products"])) //if we have the session
        {
            $found = false; //set found item to false
           
            foreach ($_SESSION["products"] as $cart_itm) //loop through session array
            {
                if($cart_itm["code"] == $product_code){ //the item exist in array

                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);
                    $found = true;
                }else{
                    //item doesn't exist in the list, just retrive old info and prepare array for session var
                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
                }
            }
           
            if($found == false) //we didn't find item in array
            {
                //add new user item in array
                $_SESSION["products"] = array_merge($product, $new_product);
            }else{
                //found user item in array list, and increased the quantity
                $_SESSION["products"] = $product;
            }
           
        }else{
            //create a new session var if does not exist
            $_SESSION["products"] = $new_product;
        }
       
    }
   
    //redirect back to original page
    header('Location:'.$return_url);
}

//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
    $product_code   = $_GET["removep"]; //get the product code to remove
    $return_url     = base64_decode($_GET["return_url"]); //get return url

   
    foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
    {
        if($cart_itm["code"]!=$product_code){ //item does,t exist in the list
            $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
        }
       
        //create a new product list for cart
        $_SESSION["products"] = $product;
    }
   
    //redirect back to original page
    header('Location:'.$return_url);
}

View Item Summary

Now we have everything ready, its time for final page where user can view their products and proceed to payment. It’s good idea to add taxes, shipping and transaction fees along with total amount in this page for the users to see. You can generate any type of data here for the Payment gateway, most Payment gateway prefer HTML form, so I have create some hidden input fields, you can modify them to suit your needs.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
session_start();
include_once("config.php");
    if(isset($_SESSION["products"]))
    {
        $total = 0;
        echo '<form method="post" action="PAYMENT-GATEWAY">';
        echo '<ul>';
        $cart_items = 0;
        foreach ($_SESSION["products"] as $cart_itm)
        {
           $product_code = $cart_itm["code"];
           $results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
           $obj = $results->fetch_object();
           
            echo '<li class="cart-itm">';
            echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
            echo '<div class="p-price">'.$currency.$obj->price.'</div>';
            echo '<div class="product-info">';
            echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
            echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
            echo '<div>'.$obj->product_desc.'</div>';
            echo '</div>';
            echo '</li>';
            $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
            $total = ($total + $subtotal);

            echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
            echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
            echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
            echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
            $cart_items ++;
           
        }
        echo '</ul>';
        echo '<span class="check-out-txt">';
        echo '<strong>Total : '.$currency.$total.'</strong>  ';
        echo '</span>';
        echo '</form>';
       
    }else{
        echo 'Your Cart is empty';
    }
?>

Continue to PHP Shopping Cart to PayPal Payment Gateway.

Download Demo

Related Articles:

214 Comments Add Comment

Comments Navigation : 1 2 3
  1. Hello,

    Thanks for this excellent tutorial! When I click “add to cart” it goes to cart_update.php and displays a blank page and never returns to my shop… I can’t find anything wrong, any ideas?

    Yours,

    Chris

    Add Reply
  2. Hi thank you for your good tutorial…

    I’ new to php, but I create simple e commerce site with your tutorial, now I’m facing issue when I removed first item in the cart not redirect return url…

    advance thanks

    Add Reply
  3. Hi,

    Cart update doesn’t add items if they already exist. eg. if you buy 2 widgets then buy another it resets back to 1. I have changed the code as follows to correct this.
    after the line:

     
    1
    if($cart_itm["code"] == $product_code){ //the item exist in array

    replace:

     
    1
    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);

    With:

     
    1
    2
    $qty_update = $product_qty + $cart_itm["qty"];
    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$qty_update, 'price'=>$cart_itm["price"]);
    Add Reply
    • not worked a webpage
      current URL of the Page. cart_update.php redirects back to this URL
      it is worked on localhost

    • Hi Muhammed
      I would like to add size or color options in the product list
      Can you help me please ?
      Thanks !

  4. Hi, thanks for this excellent tutorial. I’ve been using it with some mods with great success, but as my needs grew, I am now trying to see how I could add multiples of the same product, e.g. Android Phone FX1 Qty 2, Android Phone FX1 Qty 4 in the same cart? I bet it’s possible, but multidimensional arrays are not my strongest point. Thanks if someone can help.

    Add Reply
    • Can you explain exactly what you need? By what your saying it sounds like it does this already? I modded my version of this and it’s now almost unrecognisable from the original code. I also added sizes; Small/Med/Large as mine is for a clothing shop.

  5. Hi, the code work perfectly. Thank you.
    Now on the view-cart.php page jus below the showing products added to cart i want to put a form that for the client to complete with name, surname, email, and phone, and i want to receive the client details, and product details directly to my email address. How can i do that, i need a little help. Thx in advance.

    Add Reply
  6. What if my products that I want to sell is all about clothing,
    how to add SIZEin drop down form for example Small, Medium, Large which will display to cart update and also to view_cart.php?

    Add Reply
    • Hello kelvin,

      I had some trouble with this at first. I ended up rewriting the whole thing from the ground up. What is your PHP coding experience like as it’s actually not too difficult once you get into it.

  7. Hello

    Thank you for posting this excellent code on the internet. Really helped me learn about mysqli and designing simple code. I got everything working and I am looking to modify the code to fit my purposes. What I would like to do is to be able to update the quantity of a specific product after it has been added to the shopping cart.

    In the cart I have:

    echo ”;

    It grabs the initial quantity selected and places it into an input box in the cart. How would I modify the script to refresh the quantity for the product in the cart after I increase the input in the cart and click a button to update?

    Add Reply
    • Thanks Deanil but

      What if my products that I want to sell is all about clothing,
      how to add SIZEin form which will display to cart update and also to view_cart.php?

  8. Wow.
    You actually gave me everything which I am looking for,
    Now I think this will need some fixes as per my requirement.
    I did not try but I am going to try this,
    Thanks Alot man,
    Manu

    Add Reply
  9. i really love this website and great tutorials as we all know that class hours are very limited, still i wonder if anyone knows how this thing work if all the details regarding the product item will not come form a database instead coming from a file..i am really confused and been working for hours for that matter. can somebody help me?

    thanks in advance..

    Add Reply
  10. Notice: Undefined variable: mysql in C:\wamp\www\index.php on line 21

    Notice: Undefined variable: mysql in C:\wamp\www\index.php on line 21

    i go these errors :( help me plzzz im new in php

    Add Reply
    • What is the name of your local server my friend? Wamp or Xampp? :) I see no codes error in this tutorial. Maybe re-install your current local server and choose whether X86 for 32bit and X64 for 64bit. :) God bless

  11. Notice: Undefined variable: mysql in C:\wamp\www\index.php on line 21

    Fatal error: Call to a member function query() on a non-object in C:\wamp\www\index.php on line 21

    Add Reply
  12. I would like to do my own shipping cost and how could I pass it to paypal and for it to show the shipping cost so its added to the total. I would be very great full if you could help me.

    I have the shipping weights in a database and the weight of the items are also stored with the items in the database. I am using “$shipping2″ to call the total in the cart

    Thank you in advance

    Add Reply
  13. Good afternoon,
    First of all, thank you for this invaluable tutorial.
    I am having a problem though. When I add a product to the cart my ‘total’ shows ‘0’. I have the price in my array, the cart is showing the price for the item but the total is showing 0! Can you help me to resolve this?

    Many thanks

    Add Reply
    • Hey my friend. I also encountered that problem before. Please check your codes maybe there’s a missing opening and closing tags in echo. I also fixed that on my own. Anyway there’s no error in this tutorials. :) God bless!

  14. Good day! When I click add button and then posted in into the View Cart. How can I insert all those stuff into my database? Ex. My Product – Price – qty – date and time order (From View cart page) Looking forward for your answers. This can help me in my school project.

    Add Reply
  15. I’ve learned a lot about php in this tutorial. Thanks sir.

    Sir I have one question, what code do i have to use if I want to have quanity update in every products when I add to cart? Just like in common ecommerce site. When the customer click the “Add to Cart” you can see the 1 order in your basket. Please help sir! God bless and thanks :D

    Add Reply
  16. Hi thanks for this code it is great!!
    I am having problem with the return URL when a user removes an item from the cart.
    Instead of it returning to the correct page it directs to the Object moved page. I take the encoding off so i can see the URL and it looks correct but doesn’t work? It works fine when I set up the ‘remove’ option as a form button but not as a text link. Any hepp would be most appreciated.
    Thankyou
    Tess

    Tess

    Add Reply
  17. hey guys whats wrong here? thanks for the help :D

    Trying to get property of non-object in C:\xampp\htdocs\draft revise\order.php on line 32

    Add Reply
  18. Hi,Sir n All….
    If I m removing an item from view cart then total amount is getting Zero instead of having other items in cart.. so how to update total amount so that it decrease the removed item price from total…
    Please Give me suggestion.

    Add Reply
Comments Navigation : 1 2 3

 

Use Gravatar for Comment Pic | Start a topic for crucial discussion.


 Notify me of followup comments via e-mail. You can also subscribe without commenting.

Go Top ↑