Home  • Programming • PHP

Create a shopping cart in PHP

shopping cart product list

shopping.sql

--
-- Table structure for table `customers`
--

CREATE TABLE IF NOT EXISTS `customers` (
  `serial` int(11) NOT NULL auto_increment,
  `name` varchar(20) collate latin1_general_ci NOT NULL,
  `email` varchar(80) collate latin1_general_ci NOT NULL,
  `address` varchar(80) collate latin1_general_ci NOT NULL,
  `phone` varchar(20) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

--
-- Dumping data for table `customers`
--

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

--
-- Table structure for table `orders`
--

CREATE TABLE IF NOT EXISTS `orders` (
  `serial` int(11) NOT NULL auto_increment,
  `date` date NOT NULL,
  `customerid` int(11) NOT NULL,
  PRIMARY KEY  (`serial`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

--
-- Dumping data for table `orders`
--

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

--
-- Table structure for table `order_detail`
--

CREATE TABLE IF NOT EXISTS `order_detail` (
  `orderid` int(11) NOT NULL,
  `productid` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `price` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

--
-- Dumping data for table `order_detail`
--

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

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `serial` int(11) NOT NULL auto_increment,
  `name` varchar(20) collate latin1_general_ci NOT NULL,
  `description` varchar(255) collate latin1_general_ci NOT NULL,
  `price` float NOT NULL,
  `picture` varchar(80) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`serial`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=7 ;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`) VALUES
(1, 'View Sonic LCD', '19" View Sonic Black LCD, with 10 months warranty', 250, 'images/lcd.jpg'),
(2, 'IBM CDROM Drive', 'IBM CDROM Drive', 80, 'images/cdrom-drive.jpg'),
(3, 'Laptop Charger', 'Dell Laptop Charger with 6 months warranty', 50, 'images/charger.jpg'),
(4, 'Seagate Hard Drive', '80 GB Seagate Hard Drive in 10 months warranty', 40, 'images/hard-drive.jpg'),
(5, 'Atech Mouse', 'Black colored laser mouse. No warranty', 5, 'images/mouse.jpg'),
(6, 'Nokia 5800', 'Nokia 5800 XpressMusic is a mobile device with 3.2" widescreen display brings photos, video clips and web content to life', 299, 'images/mobile.jpg');

products.php

code for the output above
<?php
	require_once("db_config.php");
	require_once("cart_lib.php");
  
if(isset($_REQUEST['command'])){	
	if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){
		$pid=$_REQUEST['productid'];
		addtocart($pid,1);
		header("location:shoppingcart.php");
		exit();
	}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Products</title>
<script language="javascript" type="text/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=$db->query("select * from products");
			while($row=$result->fetch_assoc()){
		?>
    	<tr>
        	<td><img src="<?=$row['picture']?>"></td>
            <td>   	<b><?=$row['name']?></b><br>
            		<?=$row['description']?><br>
                    Price:<big style="color:green">
                    	$<?=$row['price']?></big><br><br>
                    <input type="button" value="Add to Cart" onClick="addtocart(<?=$row['serial']?>)">
			</td>
		</tr>
        <tr><td colspan="2"><hr size="1"></td>
        <?php } ?>
    </table>
</div>
</body>
</html>

Shopping Cart

how-the-products-will-be

shoppingcart.php

code for the picture above
<?php
	require_once("db_config.php");
	require_once("cart_lib.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>
<html>
<head>
<meta charset="utf-8">
<title>Shopping Cart</title>
<script language="javascript" type="text/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%">
    	<?php
			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>
            <?php					
				}
			?>
				<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>
			<?php
            }
			else{
				echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
			}
		?>
        </table>
    </div>
</form>
</body>
</html>

Billing Info

billing.php

code for billing info
<?php
	
	require_once("db_config.php");
	require_once("cart_lib.php");
	
	if($_REQUEST['command']=='update'){
		$name=$_REQUEST['name'];
		$email=$_REQUEST['email'];
		$address=$_REQUEST['address'];
		$phone=$_REQUEST['phone'];
		
		$result=$db->query("insert into customers values('','$name','$email','$address','$phone')");
		$customerid=$db->insert_id();
		$date=date('Y-m-d');
		$result=$db->query("insert into orders values('','$date','$customerid')");
		$orderid=$db->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);
			$db->query("insert into order_detail values ($orderid,$pid,$q,$price)");
		}
		die('Thank You! your order has been placed!');
	}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Billing Information</title>
<script language="javascript" type="text/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>

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.
indexproductidqty
02351
12392
22871
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:

cart_lib.php

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
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
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.

db_config.php

 $db=new mysqli("localhost","root","","test");

Remaining parts are coming soon....

Comments 2


If you don't understand any line of the code fragment please ask me question.
sir bujhi nai
Copyright © 2024. Powered by Intellect Software Ltd