PHP


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

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

 

 

This tutorial is about creating buttons which look similar to Facebook buttons. . Read More Facebook Button CSS

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.

fudz
[10-Sep-2010]
#50

dear Richard Clark,

 

Thanks for the code! its really easy and understand. Thanks from us.

It's really help us in developing cart in php environment!

 

TQ!

gusberrys
[03-Oct-2010]
#51

nice tutorial, when ever i click on add to cart, it doesn't add. it always says "There are no items in your shopping cart!" can please tell me what i'm missing. thanks

llasmeye
[29-Oct-2010]
#52

thanks for this awesome code! really appreciate it.

I encountered a problem though, when i access the products.php in my local server, I get a message

Notice: Undefined index: command in /opt/lampp/htdocs/shopping/products.php on line 5

on top of the list of products. :-(

 

any help will be greatly appreciated!

thanks in advance :-)

Richard
[29-Oct-2010]
#53

@llasmeye

Your php is configured to show Notices, please read http://www.php.net/manual/en/errorfunc.configuration.php to know more about Runtime Configuration

Krishana
[14-Nov-2010]
#54

Hi There

thanks for this Great code! i really appreciate it.

and for those who are having problem "Undefined index: command" just replace if($_REQUEST['command']=='add' && $_REQUEST['productid']>0)  with

if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['productid']>0)

problem will be solved

and if you still face any problem with php code in this example please replace all short php starting tags with comple php starting tags for example replace with and also replace

this code works really well just do these modifications and get this code to work well.


vicky
[31-Dec-2010]
#55

Hey, Krishna

it's not a error,only warnning.You can also Try this.

just you have to put error_reporting(0); in your db connection file. After that you never get such this type warring message. if you want to see warring message then chage value from 0 to 1.

sajuuu
[04-Jan-2011]
#56

guys im having a HUGE problem with this cart, the add button is NOT submitting, can ANYONE pplease help me

json
[02-Feb-2011]
#57

Nice & Simple - Thank you, BUT

How to get the cart contents to email?
Any help here would be great!

json
[09-Mar-2011]
#58

Remove Product Exists...

comment out this line  if(product_exists($pid)) return;
like so // if(product_exists($pid)) return;

bytes
[21-Mar-2011]
#59

does not add customer and order info to database, anyone?

Oscar
[08-Apr-2011]
#60

Have a problem with the "Update Cart" button in the shoppingcart page. The update qty works in Firefox, but not in IE. Gives me this message in IE preview Notice: Undefined index: product50114 in C:wampwwwModavilleUSA.compagesshoppingcart.php on line 15
Line 15: $q=intval($_REQUEST['product'.$pid]);
Please Advice

 

MentalSheep
[17-Apr-2011]
#61

The price field in the database should be decimal and not float to prevent aproximation errors. 

Check this for more info: http://stackoverflow.com/questions/3768713/float-or-decimal-for-prices

Igor
[19-Apr-2011]
#62

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;
}

please tell me for what  here $flag .
Thank You!

Kristen
[21-Apr-2011]
#63

This is an awesome tutorial.  I have just one question / issue.  When a product is added to the cart, and then a user tries from the product page to add that product again, nothing happens and the cart remains at the quantity of 1.  The cart itself can update quantites, but I am having a problem trying to figure out why the actual product will not increment in quantity when it already exists in the cart.  IE - product id of 1.  Added to cart successfully.  Back to product page.  Try to add another product ID 1.  Does nothing.

Jos
[30-Apr-2011]
#64

It was working fine for me then I press the button remove item then I'm not able to add any products anymore. You shopping card is empty. Any idea? I did not touch anything in the scritp.

MatcianovanWijk
[17-May-2011]
#65

When I click the add to cart button, nothing happens. Any suggestions on what I'm doing wrong?

Robert
[25-May-2011]
#66

Thanks for this great tutorial.  

As a beginner, the sample code was really helpful.  I added a line $_SESSION['cart'][$i]['qty']++; before te $flag is set to 1 to bump the cart if the same product was clicked again.  I was also wondering why the javascript is needed as the cart seems to work fine without it.  Your tutorial really made the coding clear to me.  Thanks again.

Ravinder
[15-Jun-2011]
#67

HEllo sir, i m download the code and unzipp to localhost and import database also.. but when i open my page it is blank.. not even redriect to product to product page... Please help me..

Xolani Marwanqa
[19-Jul-2011]
#68

Hi Richard Clark,

I hope I find you well.

I'm trying to run this Shopping cart on Apache Version :2.2.17 PHP Version :5.3.5, but i'm getting a blank page. Could you tell me what is coursing this.

Regards

Xola. 

Cloude
[11-Aug-2011]
#69

Hi, this script is fantastic!

but how can I send all products in my cart at paypal (with all items in cart paypal, not only the total) for payment?

thanks for help me!

adie
[05-Aug-2011]
#70

I'm trying the code, but when i clicked index.php, the products page show nothing. it just show Price : $ and add to cart button. What is the problem?

products.php :

    include("includes/db.php");
    include("includes/functions.php");
   
    if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['productid']>0){
        $pid=$_REQUEST['productid'];
        addtocart($pid,1);
        header("location:shoppingcart.php");
        exit();
    }
?>




Products






   
   

 


   

Products


   
            $result=mysql_query("select * from products");
            while($row=mysql_fetch_array($result)){
?>
   
       
           
           
       
       
       
   
      

                   

                    Price:
                        $



                   
           





 

ravi951
[19-Aug-2011]
#71

excellent for especially for beginners.

Syam Kumar Voleti
[12-Sep-2011]
#72

Thanks alot Richard. Its really awesome. I am using this code in my site.

 


Ven. Upatissa
[13-Sep-2011]
#73

I created a directory called "shopping" on my localhost, copied all of the demo files into it, executed the .sql, recreated the directyory structure, then pointed my browser to http://localhost/shopping. The items page shows up OK, with the . But when I click "add to cart" I get that same warning regarding unknown index "command" on line 5; or on the cart, lines 5, 8, and 11. Also in the cart it warns Undefined variable: msg in shoppingcart.php line 63.

I see that these is a warning, not an errors, and that if I set some lines in php.ini they will go away.  Turns out our hosting server has php.ini set up the same way, so that warnings appear on the site.  

I feel that your remarks to Nish and others is ... well, disappointing. We would certainly rather have some help than condescention. And one has to admin, a demo that doesn't work "out of the box" is egg on the lapel for the one offering the demo, wouldn't you think?

So do you think it might be possible to tweak this code (not php.ini) such that the errors, er, "warnings", do not appear?

Otherwise, the code works as advertised.

Thanking you,

Sadhu!

Web Development
[28-Sep-2011]
#74

Great coding, thanks for sharing.

yhan
[25-Oct-2011]
#75

what server that you use wampp or xampp?because it ca run with my xampp server,this error said

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

jhekjek
[05-Nov-2011]
#76

how can i fix those " Undefined index: command" in some pages, can someone help me to fixed it??

jhekjek
[12-Nov-2011]
#77

dont forget to put this code on the top " error_reporting(E_ERROR | E_PARSE); "

It will remove the undefined index ^^ and thanks to the person who give this shopping cart codes, thank you very much sir


Luis
[28-Nov-2011]
#78

When a product is choosed it is not taken by the shoppingcart.php only the "There are no items in your shopping cart!" shows up, any suggestion? I did not modified anything in the code, I downloaded the files and I just create the database and tables

horas
[04-Dec-2011]
#79

For error 

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

just replace

horas
[04-Dec-2011]
#80

sorry

just replace 

<? for <?php

Luis
[05-Dec-2011]
#81

the code at products.php seems ok, I verified the content per variable and it works fine, but at the shoppingcart.php the variables are empty, here is the code:

<?
    include("includes/db.php");
    include("includes/functions.php");
   
    if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
        remove_product($_REQUEST['pid']);
    }
    else if($_REQUEST['command']=='clear'){
        unset($_SESSION['cart']);
    }
    else if($_REQUEST['command']=='update'){
        $max=count($_SESSION['cart']);
        for($i=0;$i<$max;$i++){
            $pid=$_SESSION['cart'][$i]['productid'];
            $q=intval($_REQUEST['product'.$pid]);
            if($q>0 && $q<=999){
                $_SESSION['cart'][$i]['qty']=$q;
            }
            else{
                $msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
            }
        }
    }

?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<script language="javascript">
    function del(pid){
        if(confirm('Do you really mean to delete this item')){
            document.form1.pid.value=pid;
            document.form1.command.value='delete';
            document.form1.submit();
        }
    }
    function clear_cart(){
        if(confirm('This will empty your shopping cart, continue?')){
            document.form1.command.value='clear';
            document.form1.submit();
        }
    }
    function update_cart(){
        document.form1.command.value='update';
        document.form1.submit();
    }


</script>
</head>

<body>
<form name="form1" method="post">
<input type="hidden" name="pid" />
<input type="hidden" name="command" />
   
    <div style="margin:0px auto; width:600px;" >
    <div style="padding-bottom:10px">
        <h1 align="center">Your Shopping Cart</h1>
    <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />
    </div>
        <div style="color:#F00"><?=$msg?></div>
        <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
        <?
            if(is_array($_SESSION['cart'])){
                echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';
                $max=count($_SESSION['cart']);
                for($i=0;$i<$max;$i++){
                    $pid=$_SESSION['cart'][$i]['productid'];
                    $q=$_SESSION['cart'][$i]['qty'];
                    $pname=get_product_name($pid);
                    if($q==0) continue;
            ?>
                    <tr bgcolor="#FFFFFF"><td><?=$i+1?></td><td><?=$pname?></td>
                    <td>$ <?=get_price($pid)?></td>
                    <td><input type="text" name="product<?=$pid?>" value="<?=$q?>" maxlength="3" size="2" /></td>                   
                    <td>$ <?=get_price($pid)*$q?></td>
                    <td><a href="javascript:del(<?=$pid?>)">Remove</a></td></tr>
            <?                   
                }
            ?>
                <tr><td><b>Order Total: $<?=get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr>
            <?
            }
            else{
                echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
            }
        ?>
        </table>
    </div>
</form>
</body>
</html>

 

Luis
[05-Dec-2011]
#82

When the shoppingcart.php is opened the $_session[cart] does not exist, here is how is called this page from products.php:

 

    include("includes/db.php");
    include("includes/functions.php");
   
    if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){
        $pid=$_REQUEST['productid'];
        addtocart($pid,1);
        //print $_SESSION['cart'][0]['productid']; Works perfect 'til here!!
        header("location:shoppingcart.php");
        exit();
    }
?>

Luis Hernandez
[05-Dec-2011]
#83

Plllleeeaaaasssseeee,is anyway to see the code of the shoppingcart.php demo  because I am using the downloadable files and it does not work, pleassseee!  Thanks in advance!

Luis Hernandez
[07-Dec-2011]
#84

Anybody fix use this code right now? is anyway to get a copy? thanks

raj
[06-Jan-2012]
#85

quantity not updated when adding same product twice or more through product page...(but updated in the shopping cart text box..works fine.)

Roopa
[19-Jan-2012]
#86

hi

can any one help me to update the quantity of the product when adding the same product more than one throught the product.php page (quantity is updating in the shopping cart page by increasing the value of the text box )

Ana
[23-Jan-2012]
#87

Hey horas, I tried what you said, but it doesn`t work. I am using smarty, and want to put this into a template...if my extension is .php it works if it`s tpl it doesn`t, could you help me please?

etta
[23-Jan-2012]
#88

Hi!  Anyone knows how to show the quantity of items in the shopping cart on the header link, like: View Cart (2 items) or View Cart (0) instead of just saying 'View Cart'.    Thanks!!

cavin
[24-Jan-2012]
#89

thanks fr the code..really great help !!!

sisira
[27-Jan-2012]
#90

wow great job

help will it me a lot.

thank a lot

Mirko
[29-Jan-2012]
#91

For those who have problems with code and short codes, first of all substitute:

Then in each part where you things like:

with this echo $row['description']."
";

or 

 

This solve the problems for blank screens and not functioning buttons and so on.

Hope this will help.

vicky
[02-Feb-2012]
#92

Hi Richard

many thanks for the codes.

I created the tables in sql and uploaded all demo files to server. 

Product page is all good. it retrieves data from DB

But, when i click on add to cart...to finally go to shopping cart page...it gives me a message 

http://mysite.com/products.php?productid=1&command=add

and says...it is configured incorrectly.

pls help

 

Chidi
[10-Feb-2012]
#93

this code have build some confidence on me as a bigginer. when i click Add to Cart, it did not run. pls some body should help me

Dexon
[17-Feb-2012]
#94

thank sir very useful add to cart tutorial .

Rahul
[18-Feb-2012]
#95

Those who are facing blank page problems or able to view only $ sign and 'Add to cart' button, just do the following modifications-

1> Change or to everywhere in the code in all the files.

2> Change (and all the similar code) to

Cheers!!!

senthil
[22-Feb-2012]
#96

hi..

the program s not working...

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

if i run the products page means dis msg only should be displayed..

how to clear dis pls help..????

Madhu
[22-Feb-2012]
#97

Thanks for th info.... it would be very great if anyone posts how to retrieve the total amout and how to process it. is there any payment gateway page ?

pls do answer ASAP

Rodriges
[22-Feb-2012]
#98

The programing is not work. Where is the problem

Jason
[26-Feb-2012]
#99

Hi there,

I am getting the following at the top of the cart screen.

 

0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?>

 

doesn't generate any errors in the logs, just seems like a typo somewhere.

 

Please help

Prof Jacton opiyo
[03-Mar-2012]
#100

1. replace all <? with <php

2.t

<tr>ype ech befor $row as shown below:
            <td><img src="<?php echo $row['picture']?>" /></td>
            <td>       <b><?php echo $row['name']?></b><br />
                    <?php echo $row['description']?><br />
                    Price:<big style="color:green">
                        $<?php echo $row['price']?></big><br /><br />
                    <input type="button" value="Add to Cart" onclick="addtocart(<?php $row['serial']?>)" />
            </td>

Jag
[05-Mar-2012]
#101

dosnt work!

 

When i click add to chart

 

give me error

 


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

Notice: Undefined index: command in C:xampphtdocsshoppingshoppingcart.php on line 8

Notice: Undefined index: command in C:xampphtdocsshoppingshoppingcart.php on line 11

 

Notice: Undefined variable: msg in C:xampphtdocsshoppingshoppingcart.php on line 63

Notice: Undefined offset: 0 in C:xampphtdocsshoppingshoppingcart.php on line 70

Notice: Undefined offset: 0 in C:xampphtdocsshoppingshoppingcart.php on line 71

rajim
[10-Mar-2012]
#102

Thank's for share, code work 100%

Pardon, would you please to update this tutorial with check out system. I have spent 3 days to build without no luck, stuck once add cart without login/register. At check out process, customer force to login if registed before or register if new, then once logged or their member activated, their cart still available in cart system and automatically point to cart.php

Thank's in advance

Gurmeet
[10-Mar-2012]
#103

Great job . Nice tutorial

sam
[13-Mar-2012]
#104

Call to undefined function addtocart():how to solve this problem.please help

koustubh
[14-Mar-2012]
#105

Hi,

Great Tutorial.

If i want to add size and color to cart how can i do this?

 

 

fyra
[15-Mar-2012]
#106

erm,,,are somebody can help me?

1. at index.php not display anything..

2. at product.php , i already replace all <? to <?php but still have error?

somebody can help me to solve this error?

fyra
[15-Mar-2012]
#107

i have error like this even if already replace

please help me?

Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:xampphtdocsshoppingproducts.php on line 36

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:xampphtdocsshoppingproducts.php on line 36

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:xampphtdocsshoppingproducts.php on line 37

koustubh
[31-Mar-2012]
#108

Hi,
I have created cloths product shopping cart with help of this tutorial, I need to add size and color for products i have added following code in addtocart function

$_SESSION
['cart'][$max]['size']=$psize; $_SESSION['cart'][$max]['color']=$pcolor;

but its not added to session.

let me know what I ma doing wrong.

John
[03-Apr-2012]
#109

Hi to all,

for this who are having problem w/ the code, kindly download it here: 

http://www.sourcecodester.com/php/4220/how-build-shopping-cart-w-checkout-php.html

I just fix some minor bugs on the said tutorial. Still credit goes to Richard Clark.

I uploaded it their because I can't upload the code here.

Thanks

Ajith
[09-Apr-2012]
#110

You are an excellent TEACHER. nice post. Cheers :)

joy
[12-Apr-2012]
#111

Hi,

Thank you for the awesome tutorial. 

Would like to find out if there's any solutions for this? "quantity not updated when adding same product twice or more through product page"

Appreciate your reply!

 

babadilie
[15-Apr-2012]
#112

i have uploaded the files to my wamp server and they are working just fine. but everytime i press the clear button or the update on the shopping cart i keep getting this error

Notice: Undefined index: cart in C:wampwwwshoppingshoppingcart.php on line 92

Line 92 : if(is_array($_SESSION["cart"])){

please help me out i cant think anyway to correct this.

david
[27-Apr-2012]
#113

This guy has peculiar programming habits. If you are getting a blank index page try this.

Replace the connection string in db.php with..

 

$conn = mysql_connect("localhost","username","password");

        if(!$conn){

            die("Db Conn failed");

        }

        $dbSelect = mysql_select_db("shopping");

        if(!$dbSelect){

            die("Db not selected");

        }

session_start();

?>

 

 

asen
[08-May-2012]
#114

Hi there, I just wonder is there any chance to get the information for the order from the mysql-table

I just want to add a page where the orders can be seen Name of the custemer adress phone email what does he order and what is the price

can anyone type the function for the Mysql

thanks a lot

lenci
[09-May-2012]
#115

hej, i try to fix this code 2 days now but its not working for me why? demo looks  very nice, i realy like it but i cant get  it work :(

1. at index.php not display anything..

2. at product.php , i already replace all

 

 

I am getting the following at the top of the cart screen.

 

0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?>

 

doesn't generate any errors in the logs, just seems like a typo somewhere.

 

Richard
[09-May-2012]
#116

@lenci, please replace <? with <?php as you are using a new version of PHP

Sofus
[23-May-2012]
#117

Hi Richard

This was the best tutorial in ages. Your explanatory skills are really good.

Will keep this prominded site in my bookmarks.

Best Regards 
Sofus Comer, Denmark

ad2sound
[25-May-2012]
#118

Great Code !!!! Can i use input field on products.php to add quantity number instead of predefind vale 1 ?

Example addtocart($pid,$_REQUEST['input name']) {

..... code....

}

Thanks!!!

serkan
[27-May-2012]
#119

 

dosnt work!

 

When i click add to chart

 

give me error

 


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

Notice: Undefined index: command in C:xampphtdocsshoppingshoppingcart.php on line 8

Notice: Undefined index: command in C:xampphtdocsshoppingshoppingcart.php on line 11

 

Notice: Undefined variable: msg in C:xampphtdocsshoppingshoppingcart.php on line 63

Notice: Undefined offset: 0 in C:xampphtdocsshoppingshoppingcart.php on line 70

Notice: Undefined offset: 0 in C:xampphtdocsshoppingshoppingcart.php on line 71

 

tuong vo nhu
[07-Jun-2012]
#120

i have o error when i do this tutorial

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

anyone,can help me fix it?

thanks a lot

Ravi
[12-Jun-2012]
#121

Thanks... Really it helped me lot... once again thank you very much who uploaded this and developed this..

Rogeraj
[20-Jun-2012]
#122

Hi there even i want to regards your work

but please help me from  error accuring during runtime

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

please help me a have tried above older post of solving this error.....

Sander
[21-Jun-2012]
#123

Rogeraj, try changing line 5 into

if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['productid']>0){

Lucita
[21-Jun-2012]
#124

Thanks a lot to Richard for this excellent tutorial.

Hi Rogeraj

Replace this code:

if($_REQUEST['command']=='add' && $_REQUEST['productid']>0)

with this one:

if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['productid']>0)

I use it this morning and work perfect for me. Hope this Help!!

Rogeraj
[26-Jun-2012]
#125

Thanx for hearing me "Sander" and "Lucita"

i however managed to run the cart without any errors

and also thanx to the author of the tutorial......

hasu
[27-Jun-2012]
#126

hi

thanks Richard for your nice tutorial ..........

Is someone build a admin page for this tutorial ? if you have it please post it here .

Thanx............................

Rogeraj
[27-Jun-2012]
#127

hi again now stuck at the cart and the commend "remove" and "clear cart" are not working.....

 

Angel
[08-Jul-2012]
#128

hi! i download the file and its working all. The problem was I try to modify the table for customers because I want to add some other details to it as well as the codes in billing.php but when I try to run it in the browser it did not add customers anymore in the database. Can you help me to solve this problem? pls..ty and godbless!

ROGER
[12-Jul-2012]
#129

What a load of crap. Just look at your database. Everything is repeated twice in the order and customer table. Point is if a customers places an order, no matter how many products the OrderID should be same....Bad Example...How come no one noticed

ROGER
[12-Jul-2012]
#130

Why are all PKs repeating in the DB...Very BAD Example!!!!!

Jessy
[24-Jul-2012]
#131

First of all spot on to the author, awesome codes man! I just have a small issue though im using PHP 5.3 thru' xampp 1.7 and for some reason im getting this notice:

Notice: Undefined index: cart in C:xampphtdocsshoppingshoppingcart.php

at this line

    if (is_array($_SESSION['cart']))

 

Any help will be really appreciated.

Thanks y'all.


 

Jado Yvan
[24-Jul-2012]
#132

That seems to be good one but form u,when i try to run the project it gives me some erros like:Notice: Undefined index: command in C:xampphtdocsPROJECTCARTshoppingcart.php on line 5


Notice: Undefined index: command in C:xampphtdocsPROJECTCARTshoppingcart.php on line 8

Notice: Undefined index: command in C:xampphtdocsPROJECTCARTshoppingcart.php on line 11,

 

 

 

plz could u help me fixing this?

Simon Vetterli
[29-Jul-2012]
#133

I really like ths code. It work's for me fine.

One thing I need some help:

- how I can do, that my actual shopping cart shows always the current amount; eg if I continue to shopping but not on the products site
- What is the best way to have an admin site, wich I can admin the orders I get?

For both I need an example.

 

Kindly Simon

ajit
[10-Aug-2012]
#134

Thanks a lot to you, very good ,clear and simple shopping cart .very useful for the learners like me

dan
[13-Aug-2012]
#135

Notice: Undefined index: cart in C:xampphtdocsshoppingcart11shoppingcart.php on line 65

 

line 65: if (is_array($_SESSION['cart'])){

 

Please help me solve this error! Thanks :) Great Shopping Cart Code btw!


shevron
[17-Aug-2012]
#136

but when i tell the buyer , Thank you your order has been place, wat is the next thing?will he receive an email immediatly or wat? explain

Danny S.
[21-Aug-2012]
#137

 

Thank you, but this part of my code is not yet working. Please help me find what is wrong with it and how to correct it so my 'update cart' may work already. Please help me!!! Thanks. :(

  1. else if(isset($_REQUEST['command'])=='update'){
  2. $max=count($_SESSION['cart']);
  3. for($i=0;$i<$max;$i++){
  4. $pid=(isset($_SESSION['cart'][$i]['productid']));
  5. $q=intval($_REQUEST['product'.$pid]);
  6. if($q>0 && $q<=999){
  7. $_SESSION['cart'][$i]['qty'] = $q;
  8. }
  9. else{
  10. $msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
  11. }
  12. }
  13. }

 

Sana
[29-Aug-2012]
#138

sir thanks for this awesome tutioral....i realy appreciate you but i have a problem......i have three product categories....so i had used three products table,three products page, 3 shopping cart pages.......but the problem when only one product works ........but when i open second page.........nd select add to cart........shopping cart does not get name,price,description...only show quantinty and serial.........other fields remain blank...........although other option like update,clear,and remove is working properly..............please help me..................

Ian Dexter
[02-Sep-2012]
#139

hi.. Well the tutorial is really great , but i am not able to run it, the problem is when i clcik the "add to cart button" it will be redirected to the shoppingcart page which is definitely right, but instead to show the selected product, the shoppoing cart says " There is no product in your cart" .. Pls help thnaks

zul
[05-Sep-2012]
#140

can you provide admin page for view the order?pls...the code is good and working but i still have a problem for the admin to view the order list

sam
[08-Sep-2012]
#141

excellent tutorial,i believe you are really smart.

thank you veeerrryyyy much !!!

Cloude
[10-Sep-2012]
#142

@Jado Yvan

Hi, I have resolved in this mode:

else if(isset($_REQUEST['command']) && $_REQUEST['command'] =='clear'){

and

else if(isset($_REQUEST['command']) && $_REQUEST['command'] =='update'){

 

 

Cloude
[10-Sep-2012]
#143

Hello Richard,

This script is perfect, but can you tell me what level of security is there?

is a risk for sql injection and XSS attacks?

thanks

Gopani Bhavesh
[12-Sep-2012]
#144

Hi, I have solved this error

pls download this code

-------------------------------------------------------------------------------------
products.php
===========

<?php
     include("includes/db.php");
    include("includes/functions.php");
   
    if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' && $_REQUEST['productid']>0)
    {
        $pid=$_REQUEST['productid'];
        addtocart($pid,1);
        header("location:shoppingcart.php");
        exit();
    }
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Products</title>
<script language="javascript">
    function addtocart(pid){
        document.form1.productid.value=pid;
        document.form1.command.value='add';
        document.form1.submit();
    }
</script>
</head>


<body>
<form name="form1">
    <input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>
<div align="center">
    <h1 align="center">Products</h1>
    <table border="0" cellpadding="2px" width="600px">
        <?php
            $result=mysql_query("select * from products");
            while($row=mysql_fetch_array($result)){
        ?>
        <tr>
            <td><img src="<?php echo $row['picture']?>" /></td>
            <td>       <b><?php echo $row['name']?></b><br />
                    <?php echo $row['description']?><br />
                    Price:<big style="color:green">
                        $<?php echo $row['price']?></big><br /><br />
                    <input type="button" value="Add to Cart" onclick="addtocart(<?php echo $row['serial']?>)" />
            </td>
        </tr>
        <tr><td colspan="2"><hr size="1" /></td>
        <?php } ?>
    </table>
</div>
</body>
</html>
-------------------------------------------------------------------------------------
shoppingcart.php
================

<?php
    error_reporting(E_ERROR | E_PARSE);
   
    include("includes/db.php");
    include("includes/functions.php");
   
    if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0)
    {
        remove_product($_REQUEST['pid']);
    }
    else if(($_REQUEST['command']=='clear')){
        unset($_SESSION['cart']);
    }
    else if($_REQUEST['command']=='update'){
        $max=count($_SESSION['cart']);
        for($i=0;$i<$max;$i++){
            $pid=$_SESSION['cart'][$i]['productid'];
            $q=intval($_REQUEST['product'.$pid]);
            if($q>0 && $q<=999){
                $_SESSION['cart'][$i]['qty']=$q;
            }
            else{
                $msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
            }
        }
    }

?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<script language="javascript">
    function del(pid){
        if(confirm('Do you really mean to delete this item')){
            document.form1.pid.value=pid;
            document.form1.command.value='delete';
            document.form1.submit();
        }
    }
    function clear_cart(){
        if(confirm('This will empty your shopping cart, continue?')){
            document.form1.command.value='clear';
            document.form1.submit();
        }
    }
    function update_cart(){
        document.form1.command.value='update';
        document.form1.submit();
    }


</script>
</head>

<body>
<form name="form1" method="post">
<input type="hidden" name="pid" />
<input type="hidden" name="command" />
    <div style="margin:0px auto; width:600px;" >
    <div style="padding-bottom:10px">
        <h1 align="center">Your Shopping Cart</h1>
    <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />
    </div>
        <div style="color:#F00"><?php $msg?></div>
        <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
        <?
            if(is_array($_SESSION['cart'])){
                echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';
                $max=count($_SESSION['cart']);
                for($i=0;$i<$max;$i++){
                    $pid=$_SESSION['cart'][$i]['productid'];
                    $q=$_SESSION['cart'][$i]['qty'];
                    $pname=get_product_name($pid);
                    if($q==0) continue;
            ?>
                    <tr bgcolor="#FFFFFF"><td><?=$i+1?></td><td><?=$pname?></td>
                    <td>$ <?=get_price($pid)?></td>
                    <td><input type="text" name="product<?=$pid?>" value="<?=$q?>" maxlength="3" size="2" /></td>                   
                    <td>$ <?=get_price($pid)*$q?></td>
                    <td><a href="javascript:del(<?=$pid?>)">Remove</a></td></tr>
            <?                   
                }
            ?>
                <tr><td><b>Order Total: $<?=get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr>
            <?
            }
            else{
                echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
            }
        ?>
        </table>
    </div>
</form>
</body>
</html>
-------------------------------------------------------------------------------------
billing.php
===========

<?php
    //error_reporting(E_ERROR | E_PARSE);
   
    include("includes/db.php");
    include("includes/functions.php");
   
    if(isset($_REQUEST['command']) && $_REQUEST['command']=='update'){
        $name=$_REQUEST['name'];
        $email=$_REQUEST['email'];
        $address=$_REQUEST['address'];
        $phone=$_REQUEST['phone'];
       
        $result=mysql_query("insert into customers values('','$name','$email','$address','$phone')");
        $customerid=mysql_insert_id();
        $date=date('Y-m-d');
        $result=mysql_query("insert into orders values('','$date','$customerid')");
        $orderid=mysql_insert_id();
       
        $max=count($_SESSION['cart']);
        for($i=0;$i<$max;$i++){
            $pid=$_SESSION['cart'][$i]['productid'];
            $q=$_SESSION['cart'][$i]['qty'];
            $price=get_price($pid);
            mysql_query("insert into order_detail values ($orderid,$pid,$q,$price)");
        }
        die('Thank You! your order has been placed!');
    }
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Billing Info</title>
<script language="javascript">
    function validate(){
        var f=document.form1;
        if(f.name.value==''){
            alert('Your name is required');
            f.name.focus();
            return false;
        }
        f.command.value='update';
        f.submit();
    }
</script>
</head>


<body>
<form name="form1" onsubmit="return validate()">
    <input type="hidden" name="command" />
    <div align="center">
        <h1 align="center">Billing Info</h1>
        <table border="0" cellpadding="2px">
            <tr><td>Order Total:</td><td><?=get_order_total()?></td></tr>
            <tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
            <tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
            <tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
            <tr><td>Phone:</td><td><input type="text" name="phone" /></td></tr>
            <tr><td>&nbsp;</td><td><input type="submit" value="Place Order" /></td></tr>
        </table>
    </div>
</form>
</body>
</html>

-------------------------------------------------------------------------------------

nkhumiseni
[10-Oct-2012]
#145

thanks a lot . goog work , its wahat i needed

asdf
[27-Oct-2012]
#146

Hi all,

Im getting this error when I try to add a product to the cart:
select name from products where serial=

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

This is shown on the shoppingcart.php page, It worked fine up until today,
Any ideas on how to fix would be much appreciated.

Thanks.

Branda
[07-Nov-2012]
#147

Thanks a lot to Richard for this excellent tutorial.

Vivek
[08-Nov-2012]
#148

thanks Richard...the code works like a dream

 

shah
[07-Dec-2012]
#149

"Quick view" is also known as "quick look," among other names. It enables visitors to view product details on a category page, a cart, or any other page  without a page refresh, please show the tutorial how to do that. thanks.

Marion Praja
[12-Dec-2012]
#150

I have problem with this script:

<?
   if(is_array($_SESSION['cart'])){
             echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';
    $max=count($_SESSION['cart']);
    for($i=0;$i<$max;$i++){
     $pid=$_SESSION['cart'][$i]['productid'];
     $q=$_SESSION['cart'][$i]['qty'];
     $pname=get_product_name($pid);
     if($q==0) continue;
   ?>
              <tr bgcolor="#FFFFFF"><td><?=$i+1?></td><td><?=$pname?></td>
                    <td>$ <?=get_price($pid)?></td>
                    <td><input type="text" name="product<?=$pid?>" value="<?=$q?>" maxlength="3" size="2" /></td>                   
                    <td>$ <?=get_price($pid)*$q?></td>
                    <td><a href="javascript:del(<?=$pid?>)">Remove</a></td></tr>
   <?     
    }
   ?>

I still can not display the shopping cart ... Can you provide a way out of this problem?

frshjb373
[25-Dec-2012]
#151

I see some people have inquired about adding sizes?  Does anyone have an idea of how to implement this?  Any instruction would be extremely helpful!  Thanks in advance.

minh@yahoo.com
[11-Jan-2013]
#152

@Marion Praja

replace all <? with <?php in shoppingcart.php

Prince
[21-Jan-2013]
#153

Sir,

I want to know the code for TOTAL price in cart page..please provide it.

monir
[22-Jan-2013]
#154

Excellent tutorial.I have problem with this script: when I click Add to Cart button then it shows an error such as: Please help me.

Warning: Cannot modify header information - headers already sent by (output started at C:xampphtdocsshoppingincludesdb.php:20) in C:xampphtdocsshoppingproducts.php on line 7

hansem
[08-Feb-2013]
#155

good tutorial and work properly

kana
[08-Feb-2013]
#156

hi! i have problem with this Notice: Undefined index: cart in C:xampphtdocswebbadd2cart.php on line 70

at this line

    if (is_array($_SESSION['cart']))

 

and cart where from?

Thanks y'all.

Kountay Dwivedi
[13-Feb-2013]
#157

Thanks a lot to everyone. Truely :-)

:-}

economyip
[13-Feb-2013]
#158

Thank for this

phil
[17-Feb-2013]
#159

I am a beautician who sells hair weaves.  The customer selects the product based on texture, i.e. Deep Wave, but the price is based solely on the length of the hair, and whether it will be colored.  So I would guess that the coloring is a product in itself.  The custmer must also chose the following:

Hair Type, i.e. Brazilian, indian, etc;

Length (where the pricing is derived from), i.e., 12 inches - 100.00, 14 inches - 105.00;

Color, i.e., black, brown (note:  other colors are an extra charge - $20.00)

Shipping method (standard or overnight)

Taxes.

How would I redesign what you have given me to those options.  I know a little about databases and I know a little about options just not within the sql database... how to tie them in and their relationships.

kana
[19-Feb-2013]
#160

Please help me? all programmer i have problem with shopping cart at that line  if (is_array($_SESSION['cart'])){ it show Notice: Undefined index: cart in C:xampphtdocswebbadd2cart.php on line 70 and than show
There are no items in your shopping cart! mean that the code bellow don't work

if(is_array($_SESSION['cart'])){
       start from here-->        
echo '<tr bgcolor="#FFFFFF" style="font-weight:bold">                                   
               
<td>Picture</td>
                <td>Product</td>
                <td>Price</td>
                <td>Qty</td>
                <td>Amount</td>
                <td>Options</td></tr>';
                $max=count($_SESSION['cart']);
                for($i=0;$i<$max;$i++){
                    $pid=$_SESSION['cart'][$i]['productid'];
                    $q=$_SESSION['cart'][$i]['qty'];
                    $img=get_img($pid);
                    $pname=get_product_name($pid);
                    if($q==0) continue;
            ?>
                <tr bgcolor="#FFFFFF"><td><?php $i+1; ?></td>
                    <td><img src="<?php echo "admin/uploads/".$img;?>" width="100px"  height="100px" border="0"></td>
                    <td><?php echo $pname; ?></td>
                    <td>$ <?php echo get_price($pid) ?></td>
                    <td><input type="text" name="product<?php echo $pid; ?>" value="<?php echo $q; ?>" maxlength="3" size="2" /></td>                   
                    <td>$ <?php echo get_price($pid)*$q ?></td>
                    <td><a href="javascript:del(<?php echo $pid ?>)"><img src="images/delete_on.gif" /></a></td></tr>
            <?php                   
                }
            ?>
                <tr>
                <td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='order.php'"></td></tr>
            <?php
  arrive here-->  }
     
       else{
 and only show this word in cart-->
echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
            }

everybody know please, tell me. thank in advance.

Rutvi
[21-Feb-2013]
#161

This Tutorial is realy confidence builder... easy to understand.... thanks for sharing :)

AsianKid
[24-Feb-2013]
#162

I just figure out how to update quantity when the product already exist. 

 

 

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']){

$q = $_SESSION['cart'][$i]['qty'] +1;

$_SESSION['cart'][$i]['qty'] =$q;

$flag=1;

break;

}

}

return $flag;

}

 

Ian Haney
[02-Mar-2013]
#163

Hi

 

I am learning how to build my own shopping cart rather than using a 3rd party open source one and am using this and works perfect but just wanna know how I can get the items to carry over to PayPal and how to create a admin backend page for it and also a order confirmation page

 

Kind regards

 

Ian

surendra
[13-Mar-2013]
#164

thanks a lot,sir............

very good code......................

Imam Darmady
[19-Mar-2013]
#165

thanks for the code. i will try for my site

fidel chiko
[25-Mar-2013]
#166

0){ remove_product($_REQUEST['pid']); } else if($_REQUEST['command']=='clear'){ unset($_SESSION['cart']); } else if($_REQUEST['command']=='update'){ $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=intval($_REQUEST['product'.$pid]); if($q>0 && $q<=999){ $_SESSION['cart'][$i]['qty']=$q; } else{ $msg='Some proudcts not updated!, quantity must be a number between 1 and 999'; } } } ?>

 

 

 

 

am getting this error on shoppingcart.php   Can anyone help

Dakkar
[26-Mar-2013]
#167

Hi I have create an other db for my website and I have change the query in your file like:

$result=mysql_query("SELECT articlename FROM Shop WHERE idArticle=".$pid);

...
return $row['articlename'];

and when I clik the button add the table is not filled.
What can I do?

 

Roja
[01-Apr-2013]
#168

Hello sir,

Your code was very helpful and works good.I want to know how to get size,color etc., options also for the product before adding them to cart???

I am waiting for reply...

plz reply soon

karthik
[28-Mar-2013]
#169

Hello Richard ,thanx for the cool work so far..But Can i Know how to add sizes of a cloth along with add to cart.....

Help me.

Glenes
[18-Apr-2013]
#170

This code is working well in localhost but when I uploaded it to my webhosting some functions will not work like when you click the add to cart, it it will just display a blank page. and the url is like this product.php?productid=1&command=add.

I think this because of the js code.

Can anyone give an other idea why this happen?

jeno
[19-Apr-2013]
#171

Hi. can anybody give an idea on how to count pid's that are inside the $_SESSION['cart'];

because if I do this count($_SESSION['cart']); only one quantity every productid although there are
more than 1 quantities per productid. And if I code $_SESSION['cart']['qty'] it will also not count.

I wanna obtain this because I want to try to compute the shipping by multiplying the 
quantities to our shipping rates.

Rehman
[29-Apr-2013]
#172

When i am clicking on "add to cart" nothing is happening. please help.

Çayan
[02-May-2013]
#173

I want build a ecommerce web site with php. Thank you very much!

Rehman
[06-May-2013]
#174

Its working perfectly. thanx for the tutorial :)

but i am getting one problem. i want the shopping cart to open in the same page where the products are. when i am clicking on add to cart , the cart is opening in a new page. i tried to give in the same page but its saying A session had already been started - ignoring session_start()....andCannot redeclare get_product_name() (previously declared.... please help

Nwabisa
[20-May-2013]
#175

Hi, am getting this error when am clicking on "add to cart". .

Fatal error: Call to undefined function addtocart() in C:xampphtdocsShoppingCartproducts.php on line 9

please help.

robski
[20-May-2013]
#176

is this working in wamo? because i am using wamp and when i downlaod these files errors appear and not working too.

nilam
[22-May-2013]
#177

Hello sir,

thank you for your work, but i have a question can i use cookie instead session, is it possible? if then how what value should i set for cookie cart?

please reply asap..

thank you..

Ahmed Zayed
[11-Jun-2013]
#178

Adjust delete function so when last product in cart is removed show shopping cart is empty ..

    if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
        remove_product($_REQUEST['pid']);
                if(empty($_SESSION['cart']))
                     unset($_SESSION['cart']);
    }

tharani
[29-Jun-2013]
#179

nice tutorial .but i have select a product quantity on one page and a pass value to cart.php

tharani
[29-Jun-2013]
#180

hello

i follow  ur shopping cart tutorial nice. but i have select a product and quantity on one page. i write this code but i click addcart button not work please check mycode

products.php

<?php
    include("db.php");
    include("function.php");
    error_reporting (E_ALL ^ E_NOTICE);
    if($_REQUEST['command']=='add' && $_REQUEST['productid']>0)
     {
        $pid=$_REQUEST['productid'];
        addtocart($pid,1);
        header("location:shoppingcart.php");
        exit();
     }
   
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Products</title>
<script language="javascript">
    function addtocart(pid,qty)
    {
        document.form1.productid.value=pid;
        document.form1.quantity.value=qty;
        document.form1.command.value='add';
        alert('adding item to list');
        document.form1.submit();
    }
</script>
</head>
<body>
<form name="form1">
    <input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>
<div align="left">
    <h1 align="center">Products</h1>
    <table border="0" cellpadding="2px" width="600px">
        <?php
            $result=mysql_query("select * from products") or die("select * from products"."<br/><br/>".mysql_error());
            while($row=mysql_fetch_array($result))
            {
        ?>
        <tr>
            <td><img src="images/<?php echo  $row['image'];?>"/></td>
            <td>       <b><?php echo  $row['name']?></b><br />
                    Description:<?php echo $row['description']?><br />
                    Price:<big><?php echo $row['price']?></big><br />
                    Quantity: <input type="text" name="quantity" size="3" maxlength="3" />
                    <input type="button" value="Add To Cart" onclick="addtocart(<?php echo $row['id']?>, quantity )" />
             
            </td>
        </tr>
        <tr><td colspan="2"><hr size="1" /></td>
        <?php } ?>
    </table>
</div>
</body>
</html>

Rohit Srivastava
[02-Jul-2013]
#181

Hi .... very very thanks for this cart codes.

I want to add coupan code for discounts , how and where what code i add in this shoping cart code.

avi chitranshu
[15-Jul-2013]
#182

Sir... How we give discount on the cart lowest price  items in backend and then add grand total.

swapnil
[17-Jul-2013]
#183

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

Kulin
[20-Jul-2013]
#184

We have the same problem with swapnil.. pls help me about this.. it will be appreciated

methruwan
[24-Jul-2013]
#185

Thank u very much.Its really awsome and very helpedful for me...keep ou goooood works..

Akash
[24-Jul-2013]
#186

great upload...helped me alot  :D

akon
[26-Jul-2013]
#187

@swapnil hiii u just check u r php server and write in product page isset().

ram
[01-Aug-2013]
#188

any one can help me 

i have problem

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

khushi sharma
[06-Aug-2013]
#189

I have some problem in billing.php

order details are not inserted into database order

Bug Tan
[09-Sep-2013]
#190

How to clear the shopping cart after we do order?

anas
[29-Sep-2013]
#191

how to apply these code into my website please help

Son
[01-Oct-2013]
#192

Very useful! Thank you very much!

uzair
[02-Oct-2013]
#193

Call to undefined function addtocart() in C:wampwwwshoppingshoppingproducts.php on line 7 in product.php when i just click addtocart button

David
[12-Oct-2013]
#194

when i upload files online then i click on order button i am getting the message "There are no items in your shopping cart!" what might be the problem? but the program is working correctly in my computer

ceaden
[17-Oct-2013]
#195

why does it says "productid=undefined&command=add" what am i going to do?

shawn kirk
[25-Oct-2013]
#196

Is there anyway I can attach paypal to this so when they hit checkout they can chose to pay with paypal or google checkout?

Torben Strandberg
[05-Nov-2013]
#197

Hi Richard. Thanks for a great script. It just works exactly as it should. I'm dooing a shop for a pottery store, where products is sold in multiple sizes and colors. I know how to add the same item twice, but have problems when I update the number of one of them; both products lines are updated with the same number. How can I change this? Sincerely, Torben

Altaf Hussain
[07-Nov-2013]
#198

A very well explained article I must say. A noob coming here will end up with lots of knowledge about the shopping cart.

bob dongen
[17-Nov-2013]
#199

Hi I had whether you can help me I is with the question how do I find out what is in my cart ordered is received via mail or so that can be if the shopping cart button is clicked on the send best regards Bob

Nadimuthu
[29-Nov-2013]
#200

This is awesome.

Posting comments has been disabled temporarily