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

357 Comments Add Comment

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <?php
    session_start();
    $querystring = $_GET[‘id’];

    $idsss = explode(‘,’,$_SESSION[‘id’]);
    $quantity444 = explode(‘,’,$_SESSION[‘quantity’]);

    echo $position = array_search($querystring, $idsss);
    $new = $querystring;

    $new[$position] = $querystring;
    $idsss[]=$new;
    //$count = array_count_values($quantity444);
    //print_r($new);
    //unset($idsss[$position]);
    //unset($quantity444[$quantity444]);

    $_SESSION[‘id’] = implode(‘,’,$idsss);
    $_SESSION[‘quantity’] = implode(‘,’,$quantity444);

    echo “”;
    ?>

    this is my code.
    how can i change update quantity.plese find me

     Reply
  • How can I insert the orders into the database?

     Reply
  • I am doing online portal for holiday packages.In order to select many packages for the same head count iam ubable to get the data using codeigniter.

     Reply
  • Your quantity field is accepting negative numbers, you can probably use Math.sign() in javascript to check for negative numbers :)

     Reply
  • Please can you write out the procedural version of this code?
    I don’t really understand the object oriented PHP

     Reply
  • how can i add bank to this application?i mean how can customer pay money to bank?

     Reply
  • how to save the view_cart in mysql database?

     Reply
  • how to specific search in shooping cart ?

     Reply
  • DEBAPRIYO CHOUDHURI

    hello.

    whe m running the index.php code m getting the following error

    Notice: Undefined variable: mysqli in C:\xampp\htdocs\debo\index.php on line 9

    Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\debo\index.php on line 9

    Please suggest me what to do

     Reply
  • You are fokin awesome, man !!!!

     Reply
  • This is your code…

    $products_item .= <<<EOT

    {$obj->product_name}

    this is my code…

    $products_item .= <<<EOT

    '

    question is how can i append using your code…!!??
    when i’m using your code this ( id=”.$result[‘id’].” ) is consider as sting…. and did’nt run my file… give an error ….

    Parse error: syntax error, unexpected ” (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\cook\theme262-cookware.myshopify.com\collections\bakeware.php on line 841

    plzz resolve this

     Reply
  • please help how do i add more products?its only have 4. Is it in database? help me ty

     Reply
    • On phpMyAdmin, click on the ‘products’ table. Once you enter, there is a bar with some options above, click on ‘Insert’ and on your right, there’s a ‘Values’ section and add all the info you want to!

      Cheers!

    • u should add more products in database only

  • how do i change it to EUROS? urgent help please , ty <3

     Reply
    • On config.php, line 2, change the currency to €

    • & #8364;

      (the 7 characters have to be together, but I had to separate the ‘&’ symbol from the others because it converted me to the Euro symbol)

  • pls help me wthat fields i have to put in the database?? thank you <3

     Reply
    • I suggest you not to touch the ‘id’ field.

      You can edit ‘product_code’, ‘product_name’ and ‘price’.

      ‘product_desc’ and ‘product_img_name’ are only optional.

  • ty for your great tutorial, hmm I want something that after I click checkout it will save on my database, for example I have an table name order

     Reply
  • Hi, can anyone tell me how to save values of selected products . I need that because I want to make able those information to send to mail but don’t know how to get selected

     Reply
  • How can i add image to the table of the view_cart.php for each product i choose??
    how can i add product_img_name to the php session??
    what string have to add to cart_update.php?

     Reply
  • sir/maam how can i store the record that the user add in to cart? email me for the answer tys

     Reply
  • Hello,

    many thanks for the explain of the php shopping cart,

    i have 2 little problems,

    on the demo when i install, i would order example

    first product on black
    and first product on white,
    vut he takes only the last one, the first one is lost,

    on the index.php
    i want to show on the page only a picture wher i put a picture is in the product list.
    i tried whit the if statement but it dont work.

    can you help me

    many thanks

     Reply
  • Hello,

    manny thanks for the example of your shopping cart,

    i have 2 problems with it.

    1. if i want to order a black from the first en one White from the first he takes only the last one that i choose.

    2 on the product main page, when there is no comment of picture he dont must show, bur when there is a picture he must show.
    i tried whit a if statement, but he don’t accept.

    thx

     Reply
  • i applied those codes on my online grocery shopping but i dont know how to save my orders to databe so that it can be viewed by the admin user. Thanks

     Reply
  • hi i would like to have an option for customer to add posting product, if not it is free..
    tick button to add cost of 2 please

     Reply
  • The options are not applied correctly. If you select another product option, it’ll replace the previous selected option in the cart

     Reply
  • you coded very smartly.
    i have understand the code and apply but when i am trying to get products from another table then add to cart not work.
    can you please help me.?

     Reply
  • In “View Item Summary” code section , when I am running, it shows Undefined variable: shipping_cost , and grand_total.
    Can you please look in to the matter and check the code again?
    Thanks

     Reply
  • Notice: Undefined variable: mysqli
    Fatal error: Call to a member function query() on a non-object

     Reply
  • If is possible to remove the and AUTOINCREMENT everytime pressing “ADD button” without specific the quantity? Just via PHP itemquantity++ i think, but where?
    Or please give me some help :)

     Reply
  • What if i want to add new product using INSERT. Coz i want to have an account of admin that can add/edit products immediately.

     Reply
  • I would like to know how to push the details to payment gateway.
    Also, can u pls tell me where do you set the sessions like – $_SESSION[“cart_products”][$new_product[‘product_code’]

    I am basically trying to understand how the data is being stored, so the answer should be session . So once the checkout is done payment is done, the session is cleared automatically.
    Now in my exiting website, they are using minicart.js to do this stuff, am trying to replace that with PHP and am getting seriously confused on the flow.
    Any help on that would be really appreciated.
    Thanks in advance.

     Reply
  • watch this code with video tutorial at https://www.youtube.com/c/azazpatelweb

     Reply
  • Hi,
    thanks for the simple and working tutorial. Can you advice us on how to proceed to check out where user/system redirect to external payment gateway for example paypal and then get an email or invoice for thair purchase? a 1 last button for proceed payment i guess..thanks.

     Reply
  • Hi how can i make it in 4 columns rather than 3?

     Reply
  • HI there,
    first, thank you very much for this tutorial, your explanation very clear.
    I have a question about the code , why you include product_code while we already have product id ?

     Reply
    • Sometimes people want to set different ids for the items than the actual one. But it’s not important, you can do without it.

  • Thank you so much! this guide is simple, straightforward and gets the job done.

     Reply
  • Hi is it possible to add a fixed amount on the cart, it will reduce the amount in the cart as I add more items onto the cart. And also I would like to add an option on the cart for transport on the cart to calculate it for me

     Reply
  • hi i want that product first search by user then add in cart how to do that..in this all products are here to add in cart how only one product appear at a time..first we enter the product code in search product and then product appear how it possible

     Reply