Creating Simple Shopping Cart with PHP

Shopping Cart is very important part of any online store, it not only allows user to accumulate list of items for final purchase, but also calculates total amount of all the products. Since my last article on PayPal Express Checkout with PHP, I have received few emails asking how to create a simple PHP session based shopping cart for the website. So, keeping that in mind, today we are going to create a shopping cart, which is simple and can be integrated easily in any website that runs on 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 List

All our products information should be stored in MySql table, for that we can create a table named “products” using MySql statement below, you can insert the products details manually using PhpMyAdmin, OR use MySql file in downloadable zip, which you can import in PhpMyAdmin.

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 have database table, you can create a list of products, similar to picture below:
Product Details

Configuration

Purpose of the config file is to store various information we need for our script. Here we are just going to enter MySql authentication details to access database table. Just enter the MySql details in the configuration file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$currency = '&#8377; '; //Currency Character or code

$db_username = 'root';
$db_password = '';
$db_name = 'test';
$db_host = 'localhost';

$shipping_cost      = 1.50; //shipping cost
$taxes              = array( //List your Taxes percent here.
                            'VAT' => 12,
                            'Service Tax' => 5
                            );                     
//connect to MySql                     
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);                       
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>

Product List (Index.php)

This will be the page where you want to display the list the products you want to sell. 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 other 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. 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<div class="products">
<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
    <li class="product">
    <form method="post" action="cart_update.php">
    <div class="product-content"><h3>{$obj->product_name}</h3>
    <div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
    <div class="product-desc">{$obj->product_desc}</div>
    <div class="product-info">
    Price {$currency}{$obj->price}
   
    <fieldset>
   
    <label>
        <span>Color</span>
        <select name="product_color">
        <option value="Black">Black</option>
        <option value="Silver">Silver</option>
        </select>
    </label>
   
    <label>
        <span>Quantity</span>
        <input type="text" size="2" maxlength="2" name="product_qty" value="1" />
    </label>
   
    </fieldset>
    <input type="hidden" name="product_code" value="{$obj->product_code}" />
    <input type="hidden" name="type" value="add" />
    <input type="hidden" name="return_url" value="{$current_url}" />
    <div align="center"><button type="submit" class="add_to_cart">Add</button></div>
    </div></div>
    </form>
    </li>
EOT
;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
</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[“cart_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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
    echo '<div class="cart-view-table-front" id="view-cart">';
    echo '<h3>Your Shopping Cart</h3>';
    echo '<form method="post" action="cart_update.php">';
    echo '<table width="100%"  cellpadding="6" cellspacing="0">';
    echo '<tbody>';

    $total =0;
    $b = 0;
    foreach ($_SESSION["cart_products"] as $cart_itm)
    {
        $product_name = $cart_itm["product_name"];
        $product_qty = $cart_itm["product_qty"];
        $product_price = $cart_itm["product_price"];
        $product_code = $cart_itm["product_code"];
        $product_color = $cart_itm["product_color"];
        $bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
        echo '<tr class="'.$bg_color.'">';
        echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
        echo '<td>'.$product_name.'</td>';
        echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
        echo '</tr>';
        $subtotal = ($product_price * $product_qty);
        $total = ($total + $subtotal);
    }
    echo '<td colspan="4">';
    echo '<button type="submit">Update</button><a href="view_cart.php" class="button">Checkout</a>';
    echo '</td>';
    echo '</tbody>';
    echo '</table>';
   
    $current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
    echo '</form>';
    echo '</div>';

}
?>
</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[“cart_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
<?php
session_start(); //start session
include_once("config.php"); //include config file

//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
    foreach($_POST as $key => $value){ //add all post vars to new_product array
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
    }
    //remove unecessary vars
    unset($new_product['type']);
    unset($new_product['return_url']);
   
    //we need to get product name and price from database.
    $statement = $mysqli->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name, $price);
   
    while($statement->fetch()){
       
        //fetch product name, price from db and add to new_product array
        $new_product["product_name"] = $product_name;
        $new_product["product_price"] = $price;
       
        if(isset($_SESSION["cart_products"])){  //if session var already exist
            if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
            {
                unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
            }          
        }
        $_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item  
    }
}


//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
    //update item quantity in product session
    if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
        foreach($_POST["product_qty"] as $key => $value){
            if(is_numeric($value)){
                $_SESSION["cart_products"][$key]["product_qty"] = $value;
            }
        }
    }
    //remove an item from product session
    if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
        foreach($_POST["remove_code"] as $key){
            unset($_SESSION["cart_products"][$key]);
        }  
    }
}

//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
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
45
46
47
48
49
50
51
52
53
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%"  cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
  <tbody>
    <?php
    if(isset($_SESSION["cart_products"])) //check session var
    {
        $total = 0; //set initial total value
        $b = 0; //var for zebra stripe table
        foreach ($_SESSION["cart_products"] as $cart_itm)
        {
            //set variables to use in content below
            $product_name = $cart_itm["product_name"];
            $product_qty = $cart_itm["product_qty"];
            $product_price = $cart_itm["product_price"];
            $product_code = $cart_itm["product_code"];
            $product_color = $cart_itm["product_color"];
            $subtotal = ($product_price * $product_qty); //calculate Price x Qty
           
            $bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
            echo '<tr class="'.$bg_color.'">';
            echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
            echo '<td>'.$product_name.'</td>';
            echo '<td>'.$currency.$product_price.'</td>';
            echo '<td>'.$currency.$subtotal.'</td>';
            echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
            echo '</tr>';
            $total = ($total + $subtotal); //add subtotal to total var
        }
       
        $grand_total = $total + $shipping_cost; //grand total including shipping cost
        foreach($taxes as $key => $value){ //list and calculate all taxes in array
                $tax_amount     = round($total * ($value / 100));
                $tax_item[$key] = $tax_amount;
                $grand_total    = $grand_total + $tax_amount;  //add tax val to grand total
        }
       
        $list_tax       = '';
        foreach($tax_item as $key => $value){ //List all taxes
            $list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
        }
        $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
    }
    ?>
    <tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
    <tr><td colspan="5"><a href="index.php" class="button">Add More Items</a><button type="submit">Update</button></td></tr>
  </tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>

Continue to PHP Shopping Cart to PayPal Payment Gateway.

Download Demo

  1. Hi, how is possible to insert the cart product in DB?
    Is it possible to have different price for the same product?
    Thanks

     Reply
  2. I did it with pizzas images and It works perfectly!

     Reply
  3. Hi. I’m having an issue here.
    My code is running fine till I click on the Add button. It is simply displaying the products but then nothing happens. What should I do.
    Also, I wanna now what does this line do.
    $current_url = urlencode($url=”http://”.filter_input_array(INPUT_SERVER, ‘HTTP_HOST’) .filter_input_array(INPUT_SERVER, ‘REQUEST_URI’));
    Please reply asap. Thank you.

     Reply
  4. 1
    2
    $current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';

    What is the work of that URL sir?
    Regards Gabbuh

     Reply
  5. Does anybody know how to make the product remain with a person’s login details

     Reply
  6. Hello this code is confusing

     Reply
  7. How Can I store my cart information to the database for checkout? Please help me, Thank you in Advance!

     Reply
  8. How can I throw the informations in cart to the mysql database? Please help me, Thank you in advance!

     Reply
  9. How Can I add the cart informations and the amout payable to myql database? Please help me, Thank you in Advance!

     Reply
  10. Hi
    This tutorial is good for explaining shopping carts. But do not use it in production as you can change the shopping cart quantity to give yourself a discount. If your change a quantity of 5 to .5 you give yourself a 50% discount. Can you include js code to eliminate this security issue?

    Thanks,
    Mark

     Reply
    • JS code will not fix that issue, only help prevent it. If they disable JS on your browser, they can still change the box. You want to validate this in JS but, most importantly, validate server-side.

    • Line 45 of cart_update.php.
      add round() to the $value

      [CODE]
      $qty_update = $product_qty + $cart_itm[“qty”];
      $product[] = array(‘name’=>$cart_itm[“name”], ‘code’=>$cart_itm[“code”], ‘qty’=>$qty_update, ‘price’=>$cart_itm[“price”]);[/code]

    • Line 45 of cart_update.php.
      change $value to round($value)

      ::CODECOLORER_BLOCK_2::

  11. I have uploaded the files and when clicking the Add button to any item shown in index.php nothing happens. The View Cart module does not appear. I don’t know if it is a session issue or what. I am using Firefox 45.0 but have also tried it in IE with the same results. Any assistance would be much appreciated.

     Reply
  12. Hi this all worked perfectly for me but how to integrate with paypal express?

    This has its own index.php to work in with php form for cart and database but then how to link with

    php form in your next tutorial for paypal payment please?

     Reply
  13. The index does not display the products. Why?

     Reply
  14. Hi
    Thanks for a great toturial, have allready learned alot, and still learning, having build even further on your allready brilliant work, but now i am stuck and my skills have failed me.

    have followed your code completely in the cart_update.php file, im trying to update quantity instead of replacing it.

    currently the user put 2 products in the shopping cart and everything is fine, but when they then decide they want 1 more, they type 1 in the quantity box and clicks add to cart.

    now the code replaces the 2 allready in the cart with 1. how do i get it to just add that value to the existing value in the cart ?

     Reply
  15. Hello,
    Thank you for the nice tutorial.
    I’m beginner and almost finish my website, i need a cart so badly, i like this one and the one with jQuery.
    As beginner it’s not so easy to understand with “EOT” and i’d like to check the product stock from my database, if the stock is 0, then display a message and disable the quantity field.
    I don’t know how to do it, i tried but it’s not work, if someone can help, thank you !

     Reply
  16. I’m getting the next message once i click update cart
    Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4294967296 bytes) in /home/gallardo/public_html/shop/cart_update.php on line 23

    Where line 23 is
    $statement->bind_result($product_name, $price);

    The database has aprox 115 records.

     Reply
  17. Hi the php files do not work properly and have errors. Could you help me?

     Reply
  18. Is there a way how cart box can be hidden on a click of a button but session items will stay there

     Reply
  19. how can the prepared statement increment the rows after changing from ‘fetch_object’ to ‘fetch_assoc’?

     Reply
  20. I really like your Shopping Cart code. I am fairly new at php and I got everthing to work except, refering to the Cart View page: When I select the “Update” button I get the msg: Warning: Header may not contain more than a single header, new line detected in C:\localhost\cart_update.php on line 105.
    Is it me or is there an error there? Thanks!! Jody

     Reply
  21. Great Script !
    I want to disable the possibility for the visitor to set product quantity manually ;
    Instead, I want allow him to click on the product so that it will increment of 1 the quantity and add a row in the cart eah time he’ll click on product. Would you please to me how to do that ?
    Thanks

     Reply
  22. hello sir, i have complete my session based shopping cart but i don’t know how to add my session cart into my database please help me i am new for this..

     Reply
  23. hello sir can you remove object coding with normal (non-object programming).
    I did by myself but unable to do it. please help
    ////this code
    while($obj = $results->fetch_object())
    {
    $products_item .= <<<HTML

    {$obj->product_name}
    product_img_name}”>
    {$obj->product_desc}

    Price {$currency}{$obj->price}

    Quantity

    1
    2
    3
    4
    5

    product_code}” />

    Add

    HTML;
    }
    $products_item .= ”;
    echo $products_item;
    }
    ?>

     Reply
  24. hello i try form is good look but qty not work so please sotout error thanls

     Reply
  25. Hii,
    this Code is very useful bt after check out how i store multiple items to a database when i didnt know how my items brought by the customer…
    plz help me i need the code for my website

     Reply
  26. Nice tutorial one of the best cart scripts i have found . I would like to ask for some php help so i can include my search form into the index and make it work

     Reply
  27. Sorry for my English… It is possible add to this tutorial product variations with variable prices? In this example you use option “color” – black or silver. How to add to these options another price like “black – 150 USD” and “silver – 200 USD”? And how to add this select with another price to code and database? Can you help me?

     Reply
  28. Hi…
    thanks for Great tutorial to learn creating shopping cart in php.
    here is another tutorial too built simple shopping cart using PHP with source code . it has paypal and pay by cheque or money order functionality.

     Reply
  29. I need help. If i change the checkout button to save button, how can i save all the product in cart to database ?

     Reply
  30. Where does the order go once you paid for it?

    also, any idea how to reduce the quantity available as the items are bought?

     Reply
  31. how to get item from view_cart to order database?

     Reply
  32. in view cart, when submit….the order will got order database?

     Reply
  33. how to retrive order to admin?

     Reply
  34. Thanks for the tutorial. Works great!!!

    What would be your suggestion to keep track of orders?
    i created a orders table where i store product name, order_id, order_date, qty, total price per unit * by qty. my problem is when i order and add it to db, each item has different order_num. I want to make order_num same for multi ordered products.

    For example:

    order_num product_name qty total
    ————————————————–
    1 pencil 2 4
    1 book 1 7
    1 ruler 1 5

    Thank you, if you can help me :)

     Reply
  35. thnx a lot for this code.. simply wow..

     Reply
  36. Hi
    Why cannot I pass the value of quantity of item(when click add to cart button) from hidden input to cart_update.php?
    This is my code.I have modified a bit and cut some part to show here. Before I send to cart_update.php, I have been trying to echo it here first.
    Sound like it has something wrong with the line
    right? Is there any constraint to pass Number value in hidden field?

    <?php

    //show all products according to its category
    $result=mysqli_query($con,"select * from product where category=\"cat1\"");

    while($row = mysqli_fetch_array($result)) {

    $var1=$row['product_id'];
    $var2=$row['stock'];//number of products in stock

    echo "”;
    //select number to buy
    echo “”;
    echo “1”;
    $i=0;
    for ($i=1;$i<=$var2;$i++)
    {

    echo "$i”;
    echo “”;
    }
    echo “”;
    echo ” “;
    $varQTY =$_POST[‘select1’];

    echo “”;

    echo “”;

    echo “”;
    echo “”;

    // I try to echo here to see before sending to cart_update.php
    echo $varQTY ;
    echo “”;
    echo $_POST[‘prod_id’] ;
    echo “”;
    echo $_POST[‘prod_qty’] ; //This line cannot display the product uantity right?
    echo “”;
    echo $_POST[‘type’] ;
    echo “”;

    }

    ?>

     Reply
  37. Hi,
    How can I use an xml database. I’m trying but I can’t work with sessions.

    It’s possible

     Reply
  38. hello Dear,
    I wnt to view my cart product plz give me better solution for it .
    my product already add in my cart but not view in view_cart.php file so plz help me how to show my product in cart.

     Reply
  39. I want to ask about something, i’m trying to customize this template, and i have made the products fill less of the screen (narrower), but i would like to have 2 products on one row, but i don’t know how to if you understand what i mean? :-)
    btw awesome template/tutorial.

     Reply
  40. How to change $symbol to indian rupee symbol please send where to edit

     Reply
    • Hi there,
      You can simply change it in the config file, first line. It’s easy -:)
      cheers

  41. hello
    thanks for this post..
    but some problam create on my project that how to add selected product on my sql..
    beacuse only one product are save in mysql..
    pls help me..

     Reply
  42. How can increase and decrease Qty in view cart directly.. ?
    just want to update quantity product..

    pls help me now

     Reply
  43. nice tutorial :) But i would like to ask how i will insert the products in view cart into database in phpmyadmin?

     Reply
  44. how can i add an update cart for the quantity in view_cart.php please help me. thank you!

     Reply
  45. maybe your twitter sharebutton counter is not working :)

     Reply
  46. Hi,
    How i can print the receipt of cart box the product included in it and total bill by receipt printer and also if i want to maintain orders history the orders which are placed is that possible if it is than please help me out.provide me any tutorial or guide i will be thankful

     Reply
  47. I want to implement “Search product” in the website but I don’t know how to do it. Someone help.

     Reply
  48. hi nice tutorial, i need your help. when i select the products. click the check out. go to view_cart, in the view_cart page i want to put the pay button, now click pay button, what i select products are stored in database, how please help me

     Reply
  49. Hi,
    This is awesome tutorial! loved it ! :)
    Instead of showing products on main page, I want to have a text box where user enters the product id and then clicks on add to cart, it will automatically add that product to the cart and then checkout.
    Can you please help me out ?

     Reply

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

Ask a QuestionAllows you to ask question (one-to-one basis) and get answered.