PHP


Tutorial: Building a shopping cart in PHP
By Richard Clark
17-Jul-09
Views: 24896

This is yet another shopping cart tutorial. But the technique i will discuss is quick and easy to understand, all you need to learn this tutorial is the knowledge of PHP sessions and some array functions. So i am not going to tell you what a shopping cart is? What are sessions and how they work, i will rather jump to how we are going to build a shopping cart. But before this, you can view an online demo of this tutorial and you should also download tutorial files to your computer. Lets start!
 
How to build shopping cart (Page 1 of 1)

First of all i would like to discuss the database structure for this shopping cart. The shopping cart will have 4 tables, although the shopping process requires only 1 table i.e products, the other three tables (customers, orders and order_detail ) will be required to store successful orders. The structure of all these tables is shown below

shopping cart relationship diagram

Database Tables

ProductsThe products in this table will be shown to the user, she will add these products to her shopping cart
CustomersWhen the user places order, her billing detail will be stored in this table
OrdersThere will be a single entry for each successful order. Each order will be assigned a unique serial/order number
Order Detail There will be a single entry for each item purchased. Although price is available from the products table, but if the price of an item changes in the products table, it should not be changed in the order_detail table. So these are two different fields.

Lets now come to PHP. The shopping process will work like this:

  • The user adds a product to his/her shopping cart
  • The PHP script (products.php) receives this action and stores the requested product in the session array
  • The PHP script redirects to a different page (shoppingcart.php) which displays purchased items to the user.

How the products will be stored in the session array ?

The cart will be a 2 dimensional session array to store productid and quantity of every item purchased. The table below shows 3 items in the shopping cart.

Index productid qty
0 235 1
1 239 2
2 287 1

And the code to store these 3 items in the session array, is given below

$max=0;
$_SESSION['cart'][$max]['productid']=235;
$_SESSION['cart'][$max]['qty']=1;
 
$max++;
$_SESSION['cart'][$max]['productid']=239;
$_SESSION['cart'][$max]['qty']=2;
 
$max++;
$_SESSION['cart'][$max]['productid']=287;
$_SESSION['cart'][$max]['qty']=1;

Important Shopping Cart Functions

The following utility functions are involved in the process of shopping

addtocart
function addtocart($pid,$q){
	if($pid<1 or $q<1) return;
 
	if(is_array($_SESSION['cart'])){
		if(product_exists($pid)) return;
		$max=count($_SESSION['cart']);
		$_SESSION['cart'][$max]['productid']=$pid;
		$_SESSION['cart'][$max]['qty']=$q;
	}
	else{
		$_SESSION['cart']=array();
		$_SESSION['cart'][0]['productid']=$pid;
		$_SESSION['cart'][0]['qty']=$q;
	}
}

The addtocart function makes sure that the session variable is initialzed and then stores the received productid and quantiy to next available index. And note that there is no need to increment the $max variable


product_exists
function product_exists($pid){
	$pid=intval($pid);
	$max=count($_SESSION['cart']);
	$flag=0;
	for($i=0;$i<$max;$i++){
		if($pid==$_SESSION['cart'][$i]['productid']){
			$flag=1;
			break;
		}
	}
	return $flag;
}

The function goes through all the elements of shopping cart and checks if a products exists in the shopping cart

remove_product
function remove_product($pid){
	$pid=intval($pid);
	$max=count($_SESSION['cart']);
	for($i=0;$i<$max;$i++){
		if($pid==$_SESSION['cart'][$i]['productid']){
			unset($_SESSION['cart'][$i]);
			break;
		}
	}
	$_SESSION['cart']=array_values($_SESSION['cart']);
}

The remove_product function first finds the product and then removes the corresponding index from the session array. The last statement { $_SESSION['cart']=array_values($_SESSION['cart']) } resets the array indexes.

About PHP files in this tutorial

There are only 3 php files in the demo (in addition to functions.php and db.php file)

  • products.php (displays products to the user)
  • shoppingcart.php (displays items in the shopping cart to the user)
  • billing.php (updates customer billing information in the database)
Thats all in this tutorial. If you have any sugessions/problems or if you find any bugs, please comment below.

View Demo
Download Files in this Tutorial

 

 

Comments
thomas
[25-Jul-2009]
#1

I never thought building a shopping cart is that easy. Excellent tutorial. Thank you!

daulays
[30-Aug-2009]
#2

it's excellent thank's for that tutorial

sanjiv kumar
[01-Sep-2009]
#3

it's excellent tutorial..thanks for that.

Sarhanfx.com
[01-Sep-2009]
#4

this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a copy of this lesson on my site here www.sarhanfx.com

Olli
[01-Sep-2009]
#5

Nice tutorial, but I would prefer implementing the ShoppingCart as a class. This would offer you much more flexibility through encapsulting functionality within this class (e.g: calculateCartTotal, calculateShippingCost, and much more) In the end you serialize the instance of the cart and store it in the session. Regards...

hamid
[02-Sep-2009]
#6

easy and useful tutorial ! Could you write the next part for how add products to db with form and make admin.php page for manage orders .

Aftab
[03-Sep-2009]
#7

Thanks man u saved my life. Excellent tutorial, It would appreciate if you add the admin part as well please.

remi
[18-Sep-2009]
#8

thanx now i can feel sane.so many complicated tutorials outside.....*page bookmarked*

alexis lo
[29-Sep-2009]
#9

Hi.. why i keep getting this error (Notice: Undefined index: command in C:wampwwwshoppingproducts.php on line 5)

psboi
[05-Oct-2009]
#10

hi... nice tutorial... this is the 1 that I truly understand even that i am a beginner... but may i ask how can I load the "shopping mysql file" on my wamp server? thnx

andy
[08-Oct-2009]
#11

hi Why do i keep getting "Notice: Undefined index: command in C:Program FilesApache Software FoundationApache2.2htdocsshoppingproducts.php on line 5" ?

mgmg
[09-Oct-2009]
#12

very nice. I very like it. Please write admin form for this shopping cart. I wait your help.. Please .. very very thanks.

kastrol
[16-Oct-2009]
#13

I think improvement of function "addtocart" should be useful .. If "product_exists" return flag 1 , function would increase $q ;-)

Egypt Web Design
[17-Oct-2009]
#14

absolutely adorable ... thanks for sharing, seriously ... i love it :)

daniel
[23-Oct-2009]
#15

Great Tutorial. Can you let me know the field structure (name and number os characyers) of each of the 4 tables? Thanks daniel.

markos
[29-Oct-2009]
#16

waw ill try to use it in my weblog www.pokeerpro.talk4fun.net thanks bro richard

Michiel
[04-Nov-2009]
#17

Great tut! I'm using it as we speak. :D But the big Q i have; how can i send an e-mail to the customer with the order? Many thanks!

Loren
[18-Nov-2009]
#18

Whoa!!! nice tutorial... I didn't know it was so easy!!! Thanks a million!

Harpreet Sohal
[21-Nov-2009]
#19

waoo................nice tutorial

happy user
[21-Nov-2009]
#20

Awesome tutorial good job! you saved my life!! :)

Jason
[12-Dec-2009]
#21

I found bug when I test demo added items then removed each items then notice not empty just say 0. If I clicked all clear then it will normal empty shopping cart. Just click remove items each then see there still not emtpy. It's bug script somewhere session still stuck without delete.

Marcio
[17-Jan-2010]
#22

Exelente tutorial , parabens!

rizwan
[02-Feb-2010]
#23

Some text comments

Avinash
[05-Feb-2010]
#24

PLease give me SQL query to retrive the order placed and the total price

Nish
[04-Mar-2010]
#25

Hi I get this error when running the code...HELP PLEASE!

Notice: Undefined index: command in C:wampwwwshoppingproducts.php on line 5

Richard Clark
[04-Mar-2010]
#26

@Nish You should learn some php before you can start creating shopping carts in php

juve
[01-Apr-2010]
#27

when i open site there is blank site...Index is blank. Anybody know what is wrong?

rely7
[05-Apr-2010]
#28

I have the same problem, index blank. I appreciate your help.

Richard Clark
[05-Apr-2010]
#29

juve & reply7

You might be using Internet Explorer 6? Are u

rely7
[05-Apr-2010]
#30

Thanks for your prompt reply. I'm using Mozilla Firefox.

rely7
[05-Apr-2010]
#31

This is the error I got at the top of products.php. It seems that it doesn't pick up data from DB.

0){ $pid=$_REQUEST['productid']; addtocart($pid,1); header("location:shoppingcart.php"); exit(); } ?>

j b
[09-Apr-2010]
#32

I have been trying to use the shopping code and I am stuck with the 'addtocart' javascript code not working. Below is snippet that seems to be the problem. If I remove the references to 'document....' the alert pops up. This means that the PHP 'addtocart' never gets called. Any ideas?

Thanks,

 

JB

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<script language="javascript">

function addtolist( flower, qty, price ) {

document.myform.flower.value = flower;

document.myform.quantity.value = qty;

document.myform.cost.value = price;

document.myform.command.value = 'add';

alert('adding item to list');

document.myform.submit( );

}

</script>

</head>

 

<body style="background: #666633; margin: 0px;">

<form name="myform">

<br>

Order Quantity: <input name="quantity" type="text" maxlength="4" /><input type="hidden" name="flower" value="Some Text"/><input type="hidden" name="cost" value="25.00"/><input type="button" value = "Add" onclick="addtolist( flower, quantity, cost )"  />

</form>

</body>

</html>

j b
[10-Apr-2010]
#33

I have some of it working. The scenario is this: instead of going to the shopping cart page every time the customer clicks the 'add to cart' button, he/she remains on the product page but the item is added to the cart. The php code 'if ($_REQUEST[ 'command' ] == 'add' && $_REQUEST[ 'quantity' ] != 0 ) {...' is never called which means the 'addtocart' in 'functions.php' is never called. What am I missing? Any ideas?

<p>BTW, I am using multiple forms. Each item has it's own 'form' as in the following:</p>
<p><span style="white-space: pre;;"> </span><span style="font-family: Verdana, Geneva, sans-serif; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px;;">&nbsp;</span></p>
<form>
<p>&nbsp;</p>
<p><span style="font-family: Verdana, Geneva, sans-serif; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px;;"> </span></p>
<p><span style="white-space: pre;;"> </span></p>
<p><span style="white-space: pre;;"> </span>Order Quantity: <input maxlength="4" name="quantity" type="text" /><input name="flower" type="hidden" value="Some Text" /><input name="cost" type="hidden" value="25.00" /><input onclick="addtolist( flower, quantity, cost )" type="button" value="Add" /></p>
<p><span style="white-space: pre;;"> </span></p>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<form>
<p>&nbsp;</p>
<p><span style="white-space: pre;;"> </span></p>
<p><span style="white-space: pre;;"> </span>Order Quantity: <input maxlength="4" name="quantity" type="text" /><input name="flower" type="hidden" value="Some Text" /><input name="cost" type="hidden" value="25.00" /><input onclick="addtolist( flower, quantity, cost )" type="button" value="Add" /></p>
<p><span style="white-space: pre;;"> </span></p>
</form>

 

 

 

Thanks,

JB

Richard Clark
[10-Apr-2010]
#34

@JB "BTW, I am using multiple forms"

Any reason for using multiple forms. What you can't achieve with a single form? Remember you will be able to submit only 1 form

moses
[02-May-2010]
#35

Nice tutorial man I appreciate this,can you add feature for this tutorial and image upload section for this tutorial.Thanks man.

Peter
[14-May-2010]
#36

hello everyone ,how would i show total items in the cart , i mean after i update the items i get the total cost .Like that i want to show total items .

does anyone please show me some example , please.

dore
[15-May-2010]
#37

how do i make the qty increase each time the 'add cart' button is pushed on?

MediaMore
[20-May-2010]
#38

Great tutorial, very easy for understanding and useful!

Web Development
[13-Jun-2010]
#39

That's a great tutorial, it sounds friendly and works well for cart designing.

Cem
[07-Jul-2010]
#40

thanks!!

Pranav
[28-Jul-2010]
#41

Where can we download the complete code. The code for download over here is incomplete

Pranav
[28-Jul-2010]
#42

Whats the use of the javascript function used in products.php?

Raja
[06-Aug-2010]
#43

Thank u very much , it is great , its helped me very much, keep it up guys

ELIAS ESCOBAR
[09-Aug-2010]
#44

Nice tutorial, thank a lot

Muchas Gracias

Cor Claessen
[22-Aug-2010]
#45

Hi Richard,

Thanks for this, great. I have a question. Can you tell me how to add up the total quantities of the products when ordering? If I can add them up I can establish the shipping costs...

Thanks again and best regards,

Cor Claessen

Cor Claessen
[23-Aug-2010]
#46

Hi Richard,

Thanks, but I think I figured it out myself. Put another record in the products tabel where I can put in the weight. By checkout, you can add up the values and get your shipping costs.

By the way, is it wise to call this table 'products'? The same goes for 'order' and 'order_detail'?

Thnx,

Cor Claessen

kat
[03-Sep-2010]
#47

Thanks for this good tutorial! Saved me. :))

tonyalfrey
[05-Sep-2010]
#48

This really looks great but I'm a total amateur at php and MySQL.  I'm using MAMP to act as a php server for other shopping carts I've tried, but I'm not sure how to incorporate MySQL.  I tried to start the tutorial from MAMP and also put the tutorial on my webpage but I get "Demo is not available, please try again later" in both cases.  I see from the php code that it seems that it can't find a MySQL server.  Any help greatly appreciated.  Thanks in advance.

tonyalfrey
[05-Sep-2010]
#49

Never mind.  I discovered that I had to take the shopping.sql database and actually put it someplace where the MySQL server looks for all of the databases.  I really have no idea what I actually did, but now it is working.

Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Are you human ?

Enter the code shown above