Create Simple Shopping Cart with PHP and Mysql

Any Online store cannot be managed without shopping cart. Almost all Famous E-commerce  scripts like Magento, OpenCart , osCommerce etc  have most of their powerful  from their different shapes of shopping carts. In this tutorial, you will learn how to make a simple php shopping cart. An online shopping basket is important part of E-commerce platform.

Step 1:

Make the database where you will store your apps data. We need to store general information about the order (order id, order date, shipping fee, shipping name, shipping street, email, phone, whether it is submitted or not) and the details of each  order.
We will use two tables

1. orders table to save new orders.

CREATE TABLE IF NOT EXISTS `order_items` (
  `id` int(14) NOT NULL AUTO_INCREMENT,
  `order_id` int(14) NOT NULL,
  `item_number` int(4) NOT NULL,
  `item_name` varchar(255) NOT NULL,
  `quantity` decimal(9,2) NOT NULL,
  `price` decimal(9,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=39 ;

2. order_items table to save orders' items in details.

CREATE TABLE IF NOT EXISTS `orders` (
  `id` int(14) NOT NULL AUTO_INCREMENT,
  `date` datetime NOT NULL,
  `ship_fee` decimal(9,2) NOT NULL,
  `ship_name` varchar(255) NOT NULL,
  `Ship_street` varchar(255) NOT NULL,
  `ship_city` varchar(50) NOT NULL,
  `ship_state` varchar(50) NOT NULL,
  `sales_tax` float NOT NULL,
  `submitted` int(1) NOT NULL DEFAULT '0',
  `email` varchar(50) NOT NULL,
  `phone` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

Step 2:

Write the code that connect php script to database

<?php
define('host','localhost');
define('username','root');
define('password','');
define('database','');

// establish connection
$connection = mysqli_connect(host,username,password) or die("Cannot connect to the server");

$connect_db = mysqli_select_db($connection,database)or die("Cannot connect to database");
?>

Step 3:

Make the items web page where users add items to the cart , delete them and see the items added to their cart .
index.php file can do some functions determined by selected action:

  • make new order
  • add new items to orders
  • delete items from orders
  • add one item to the same items ‘type.
  • minus one item from the same item’s type.
  • delete all items from an order.
<?php
session_start();
include('config.php');

if(isset($_GET['do'])){ // check request from page forms
	$action = $_GET['do'];
	//Array ( [quantity] => 1 [item_number] => 2 [item_name] => pant [item_price] => 38 ) Array ( [do] => add ) 
	switch($action){
	case"add":
	// code of adding new items to the order
	// first get item details in variables
		$item_number = mysql_real_escape_string($_POST['item_number']);
		$item_name = mysql_real_escape_string($_POST['item_name']);
		$item_price = mysql_real_escape_string($_POST['item_price']);	
		$quantity = mysql_real_escape_string($_POST['quantity']);	
		// check if there is an existing order from the session where we save session id 
		if(!isset($_SESSION['order_id'])) 
		{ // if there isn't an order, make new order in orders table and save its id in session array
			
			$today = date('Y-m-d : h-i-s');
			$sql_order = "INSERT INTO orders (date) VALUES ('$today')";
			$result = mysqli_query($connection,$sql_order) or die(mysqli_error($connection));
			$order_id = mysqli_insert_id($connection);
			$_SESSION['order_id'] = $order_id;
			
		}
		else 
		{
			//if there is an order , count items in order has the same type of added item
			$order_id = $_SESSION['order_id'];
			$sql_item_quantity = "select count(*) as quantity  from order_items where order_id =$order_id and item_number = $item_number";
			$result = mysqli_query($connection,$sql_item_quantity)or die(mysqli_error($connection));
			$row = mysqli_fetch_assoc($result);

		    $item_quantity = $row['quantity'];//$result->fetch_assoc()['quantity'];//$row[0];

			
		}
		//now we will add the new item <br>
		// if there is one or more from this item we only update the record of existed item .add one to the quantity and add an item price to the existing cost 
		if( intval($item_quantity) >= 1 ){
			$sql_add_item = "Update order_items set quantity=quantity+1 , price = price + $item_price";
			
		}else{ 
		// there is no items in the same type .so,we make a new record to add the item
			$sql_add_item = "INSERT INTO order_items (order_id,item_number,item_name,quantity,price ) VALUES ($order_id,$item_number,'$item_name',$quantity,$item_price)";
			
		}
		$result = mysqli_query($connection,$sql_add_item) or die(mysqli_error($connection));
		if($result){
			$msg = "item was add";
		}else{
			$msg = "Cannot add item";
		}			
	break;	
	case"delete":
	// Code of deleting a spesific items details from order 
		$item_id = intval($_GET['id']);
		$order_id = $_SESSION['order_id'];
		$sql_item_delete = "DELETE FROM order_items where order_id = $order_id and id = $item_id ";
		$result = mysqli_query($connection,$sql_item_delete)or die(mysqli_error($connection).'-'. $sql_item_delete);
		if($result){
			$msg = "item was deleted";
		}else{
			$msg = "Cannot delete item";
		}	
		
	break;
	case"delete_all":
	// Code of deleting all items from order 
		$order_id = $_SESSION['order_id'];
		$sql_item_delete = "DELETE FROM order_items where order_id = $order_id ";
		$result = mysqli_query($connection,$sql_item_delete)or die(mysqli_error($connection));
		if($result){
			$msg = "Cart is empty";
		}else{
			$msg = "Cannot empty cart";
		}		
	break;
	case"add_one":
	//  Code of increasing the quantity of an item by one 
		$item_id = intval($_GET['id']);
		$order_id = $_SESSION['order_id'];
		$sql_add_item = "Update order_items set quantity=quantity+1 , price = ( price /( quantity - 1) ) * quantity where id =$item_id";
		$result = mysqli_query($connection,$sql_add_item)or die(mysqli_error($connection).'-'. $sql_item_delete);
		if($result){
			$msg = "item was added";
		}else{
			$msg = "Cannot add item";
		}	
	
	break;
	case"remove_one":
	//  Code of decreasing the quantity of an item by one 	
		$item_id = intval($_GET['id']);
		$order_id = $_SESSION['order_id'];
		$sql_remove_item = "Update order_items set quantity=quantity-1 , price = ( price /( quantity + 1) ) * quantity where id =$item_id";
		$result = mysqli_query($connection,$sql_remove_item)or die(mysqli_error($connection).'-'. $sql_item_delete);
		if($result){
			$msg = "item was removed";
		}else{
			$msg = "Cannot remove item";
		}		
		break;
			
		
	}	
	
}

if(isset($_SESSION['order_id'])){
	// getting the saved items in the existing order
	$order_id = mysql_real_escape_string($_SESSION['order_id']) ;
	$sql_get_order_items = "select * from order_items where order_id =$order_id ";
	$cart_data = mysqli_query($connection,$sql_get_order_items)or die(mysqli_error($connection));
	$items_number = mysqli_num_rows($cart_data);
	
} 

// get the view code from template file
include("cart_template.php");

?>

cart_template.php

cart_template.php file view items of shopping cart if exist, buttons to control items  and the items forms catalog.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
      <!-- compatitbility meta -->
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <!--  Mobile meta -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

<title>Simple shopping cart - Discussdesk</title>

   <!--[if lt IE 9]>
 <script src="js/html5shiv.min.js"></script> 
<script src="js/respond.min.js"></script>
    <![endif]-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>
 
	<div class="container" >
    <?php if(@$msg){ ?>
		<div class="alert alert-danger" role="alert">
          <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
          <span class="sr-only"></span>
          <?=$msg?>
        </div>
		
	<?php 	} ?>
    <div class="panel panel-default">
      <!-- Panel of the ordered items in cart -->
      <div class="panel-heading">Your cart <?php if (@$items_number < 1){ echo" is empty"; }?></div>
      
    
      <!-- Table -->
		<table class="table"> 
        	<thead>
            	 <tr> <th>#</th> <th>item name</th> <th>quantity</th> <th>price</th><th>control</th> </tr> 
            </thead>
             
            <tbody> 
            <?php if (@$items_number >= 1){ // if order have one item or more loop in it and make a list of items in cart
				$n = 1;
				$total = 0;
				while($item = mysqli_fetch_array($cart_data)){
					
				 ?>
                <tr> <th scope="row"><?=$n?></th> <td><?=$item['item_name']?></td> <td><?=$item['quantity']?></td> <td><?=$item['price']?>$</td> <td><a href="cart.php?do=delete&id=<?=$item['id']?>"><span class="btn btn-danger" >remove </span></a>   <a href="cart.php?do=add_one&id=<?=$item['id']?>"><span class="btn btn-success" >+ </span></a> <a href="cart.php?do=remove_one&id=<?=$item['id']?>"><span class="btn btn-warning" >- </span></a>  </td> </tr>
                <?php
				$n++;
				$total +=$item['price'];
				 }}?>
 
            </tbody> 
            <tfoot>
            	 <tr> <th>#</th> <th>total</th> <th></th> <th><?php echo(@$total)?$total:'0'; ?>$</th> <th></th></tr>
            </tfoot>
		</table>
        <div class="panel-body btn-group btn-group-justified">
        <div class="panel-footer" >
        	<div class="btn-group col-md-4" role="group">
              <a href="cart.php?do=delete_all"><span class="btn btn-default col-md-8" >empty cart</span></a>
 
          </div>
          <div class="btn-group col-md-4" role="group">
          	<a href="submit_order.php"><span class="btn btn-default col-md-8" >submit order</span></a>
          </div>

          </div>
        
      </div>
    </div>
    <!-- Items and its forms where you can add new items -->
    <div class="row">
  
    <div class="col-md-3 simpleCart_shelfItem">   
<div class="panel panel-default">
     <div class="panel-heading item_name">T shirt </div>
  <div class="panel-body">
 <img src="img/t-shirt.jpg" class="img-thumbnail img-responsive item_thumb"><br> 
     <p class='input-sm clearfix'>Description of the product </p><span class='row'></span>
  </div>
  <div class="panel-footer"> <p class="item_price">$ 88</p>
  <form method="post" action="?do=add" >
  <input type="submit" class='btn btn-danger btn-md item_add' value="ADD" >
 
  
      <label>Qty: <input class="item_Quantity form-control" type="text"  name="quantity" value="1"></label>
    <input type="hidden" name="item_number" value="1">
    <input type="hidden" name="item_name" value="Tshirt">
     <input type="hidden" name="item_price" value="88">  
    </form>  
     </div>
</div>
</div><!-- end object -->

 <div class="col-md-3 simpleCart_shelfItem">   
<div class="panel panel-default">
     <div class="panel-heading item_name">Pant</div>
  <div class="panel-body">
 <img src="img/pant.jpg" class="img-thumbnail img-responsive item_thumb"><br>Description
  </div>
  <div class="panel-footer"><p class="item_price">$ 38</p>  
    <form method="post" action="?do=add" >
  <input type="submit" class='btn btn-danger btn-md item_add' value="ADD" >
    <label>Qty: <input class="item_Quantity form-control" type="text" name="quantity" value="1"></label>
    <input type="hidden" name="item_number" value="2">
    <input type="hidden" name="item_name" value="pant">  
         <input type="hidden" name="item_price" value="38"> 
    </form>  
    </div>
</div>

</div><!-- end object -->
     <div class="col-md-3 simpleCart_shelfItem">   
<div class="panel panel-default">
     <div class="panel-heading item_name">Jacket</div>
  <div class="panel-body">
  <img src="img/jacket.jpg" class="img-thumbnail img-responsive item_thumb"><br>Description
  </div>
  <div class="panel-footer"><p class="item_price">$ 348</p> 
    <form method="post" action="?do=add" >
  <input type="submit" class='btn btn-danger btn-md item_add' value="ADD" >
  <label>Qty: <input class="item_Quantity form-control" type="text"  name="quantity" value="1"></label>
      <input type="hidden" name="item_number" value="3">
    <input type="hidden" name="item_name" value="jacket">  
         <input type="hidden" name="item_price" value="38">    
    </form>  
  </div>
</div>
</div>
</div>
    	
	</div>


<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>

</body>
</html>

Step 4:

After the user select order’s items , he should click ( submit order ) link to go to submit_order.php page.submit_order.php needs the data of the order itself then it save it in database and unset the order id element  in session array .

submit_order.php

<?php
session_start();
include('config.php');
if(isset($_POST['save_order'])){
	if(empty($_POST['ship_name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['ship_state']) || empty($_POST['ship_city']) ||  empty($_POST['ship_street'])){
		$msg = "Please ,complete order data ";
	}else{
		$ship_name = mysql_real_escape_string($_POST['ship_name']);
		$email = mysql_real_escape_string($_POST['email']);
		$phone = mysql_real_escape_string($_POST['phone']);
		$ship_state = mysql_real_escape_string($_POST['ship_state']);
		$ship_city = mysql_real_escape_string($_POST['ship_city']);
		$ship_street = mysql_real_escape_string($_POST['ship_street']);
												
			
		$order_id = mysql_real_escape_string($_SESSION['order_id']) ;
		$sql_get_save_order = "UPDATE orders set ship_name='$ship_name',email='$email',phone='$phone',ship_state='$ship_state',ship_city='$ship_city',ship_street='$ship_street' where id = $order_id ";
		$save_order = mysqli_query($connection,$sql_get_save_order)or die(mysqli_error($connection));
		if($save_order){
			print_r($_SESSION);
			unset($_SESSION['order_id']);
			print_r($_SESSION);
			die( "Your order was successfully saved . It will be delivered soon <br />
	Go to <a href='cart.php'>items page  </a>");
		}else{
			$msg = "Cannot save your order, please try again !"	;
		}
		
		
	}
}

if(isset($_SESSION['order_id'])){
	// getting the saved items in the existing order
	$order_id = mysql_real_escape_string($_SESSION['order_id']) ;
	$sql_get_order_items = "select * from order_items where order_id =$order_id ";
	$cart_data = mysqli_query($connection,$sql_get_order_items)or die(mysqli_error($connection));
	$items_number = mysqli_num_rows($cart_data);
	
}else{
	header("Location:cart.php");
	} 
if($items_number < 1){
	die( "You didn't add any utems to your order ! <br />
	Go to  <a href='cart.php'>items page </a>");
	}
	include("submit_order_template.php");
?>

    

submit_order_template.php

submit_order_template.php file contains the checkout table and the form who save order details.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
      <!-- compatitbility meta -->
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <!--  Mobile meta -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

<title>Simple shopping cart - Discussdesk</title>

   <!--[if lt IE 9]>
 <script src="js/html5shiv.min.js"></script> 
<script src="js/respond.min.js"></script>
    <![endif]-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>
 
	<div class="container" >
        <?php if(@$msg){ ?>
		<div class="alert alert-danger" role="alert">
          <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
          <span class="sr-only"></span>
          <?=$msg?>
        </div>
		
	<?php 	} ?>
    <div class="panel panel-default">
    <form method="post" action="" >
      <!-- Panel of the ordered items in cart -->
      <div class="panel-heading">Your order </div>
      
    
      <!-- Table -->
		<table class="table"> 
        	<thead>
            	 <tr> <th>#</th> <th>item name</th> <th>quantity</th> <th>price</th></tr> 
            </thead>
             
            <tbody> 
            <?php if ($items_number >= 1){ // if order have one item or more loop in it and make a list of items in cart
				$n = 1;
				$total = 0;
				while($item = mysqli_fetch_array($cart_data)){
					
				 ?>
                <tr> <th scope="row"><?=$n?></th> <td><?=$item['item_name']?></td> <td><?=$item['quantity']?></td> <td><?=$item['price']?>$</td> </tr>
                <?php
				$n++;
				$total +=$item['price'];
				 }}?>
 
            </tbody> 
            <tfoot>
            	 <tr> <th>#</th> <th>total</th> <th></th> <th><?php echo(@$total)?$total:'0'; ?>$</th> </tr>
            </tfoot>
		</table>
        <div class="panel-heading">Please fill you order detail</div>
        
        <table class="table"> 
<!--        	<thead>
            	 <tr> <th>#</th> <th>item name</th> <th>quantity</th> <th>price</th></tr> 
            </thead>   -->
             
            <tbody> 

                <tr> <th scope="row">Name</td> <td><input type="text"  name="ship_name" placeholder="name"></td>  </tr>
                <tr> <th scope="row">Email</td> <td><input type="email"  name="email" placeholder="email"></td>  </tr>
                <tr> <th scope="row">Phone</td> <td><input type="text"  name="phone" placeholder="phone"></td>  </tr>
                <tr> <th scope="row">State</td> <td><input type="text"  name="ship_state" placeholder="ship_state"></td>  </tr>
                <tr> <th scope="row">City</td> <td><input type="text"  name="ship_city" placeholder="ship_city"></td>  </tr>
                <tr> <th scope="row">Street</td> <td><input type="text"  name="ship_street" placeholder="ship_street"></td>  </tr>
              </tbody> 
            
		</table>
        <div class="panel-body btn-group btn-group-justified">
        <div class="panel-footer" >
        	<div class="btn-group col-md-4" role="group">
            
              <a href="cart.php"><span class="btn btn-default col-md-8" >items page</span></a>
 
          </div>
          <div class="btn-group col-md-4" role="group">
          <button type="submit" name="save_order" class="btn btn-default col-md-8"  >submit order</button>
          	
          </div>

          </div>
          </div>
          </form>
        
      </div>
    </div>
    
    </div>
</body>
</html>

Now you are able to Create your own shopping cart. If you have any query, feel free to ask in comment section.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments