PHP - Simple Shopping Cart

In this tutorial we will create a Simple Shopping Cart using PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by a newly coders for its user friendly environment. So Let's do the coding...

Before we get started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_shopping, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2.         $conn = new mysqli("localhost", "root", "", "db_shopping");
  3.        
  4.         if(!$conn){
  5.                 die("Error: Failed to connect to database");
  6.         }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as shown below. index.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <meta charset="URF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-7 well">
  14.                 <h3 class="text-primary">PHP - Simple Shopping Cart</h3>
  15.                 <hr style="border-top:1px dotted #ccc;"/>
  16.                 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#form_modal"><span class="glyphicon glyphicon-plus"></span> Add Product</button>
  17.                 <br /><br />
  18.                         <?php
  19.                                 require 'conn.php';
  20.  
  21.                                 $query = $conn->query("SELECT * FROM `product` ORDER BY `product_price` DESC");
  22.                                 while($fetch = $query->fetch_array()){
  23.                         ?>
  24.                         <div class="pull-left" style="height:350px; width:220px; margin:8px; border:1px solid #000; padding:5px; border-radius:5px;">
  25.                                 <center><img src="<?php echo $fetch['image']?>" height="150px" width="180px"/></center>
  26.                                 <center><h4><strong><?php echo $fetch['product_name']?></strong></h4></center>
  27.                                 <center><h4 class="text-danger">&#8369; <?php echo number_format($fetch['product_price'])?></h4></center>
  28.                                 <form method="POST" action="addcart.php?id=<?php echo $fetch['product_id']?>">
  29.                                         <input type="hidden" name="product_name" value="<?php echo $fetch['product_name']?>"/>
  30.                                         <input type="hidden" name="product_price" value="<?php echo $fetch['product_price']?>"/>
  31.                                         <center><input type="number" name="qty"/></center>
  32.                                         <br />
  33.                                         <center><button class="btn btn-success" name="add"><span class="glyphicon glyphicon-shopping-cart"></span> Add to cart</button></center>
  34.                                 </form>
  35.                         </div>
  36.                         <?php
  37.                                 }
  38.                         ?>
  39.         </div>
  40.         <div class="col-md-5">
  41.                 <div class="alert alert-info">
  42.                         <h2>Orders</h2>
  43.                 </div>
  44.                 <table class="table table-bordered">
  45.                         <thead>
  46.                                 <tr>
  47.                                         <th>Product Name</th>
  48.                                         <th>Price</th>
  49.                                         <th>Qty</th>
  50.                                         <th>Total</th>
  51.                                         <th>Action</th>
  52.                                 </tr>
  53.                         </thead>
  54.                         <tbody>
  55.                                 <?php
  56.                                         session_start();
  57.                                        
  58.                                         if(!empty($_SESSION["cart"])){
  59.                                                 $total = 0;
  60.                                                 foreach($_SESSION["cart"] as $keys => $values){
  61.                                                        
  62.                                 ?>
  63.                                 <tr>
  64.                                         <td><?php echo $values['product_name']?></td>
  65.                                         <td>&#8369;  <?php echo number_format($values['product_price'])?></td>
  66.                                         <td><?php echo $values['qty']?></td>
  67.                                         <td>&#8369;  <?php echo number_format($values['qty'] * $values['product_price'])?></td>
  68.                                         <td><center><a class="btn btn-danger" href="delete.php?id=<?php echo $values['product_id']?>"><span class="glyphicon glyphicon-remove"></span></a></center></td>
  69.                                 </tr>
  70.                                 <?php
  71.                                                 $total = $total + ($values['qty'] * $values['product_price']);
  72.                                                 }
  73.                                 ?>
  74.                                         <tr>
  75.                                                 <td colspan="3" align="right">Total</td>
  76.                                                 <td>&#8369;  <?php echo number_format($total) ?></td>
  77.                                                 <td><a href="purchase.php" class="btn btn-info"><span class="glyphicon glyphicon-ok"></span> Buy</a></td>
  78.                                         </tr>
  79.                                 <?php
  80.                                                
  81.                                         }
  82.                                 ?>
  83.                         </tbody>
  84.                 </table>
  85.        
  86.         </div>
  87.         <div class="modal fade" id="form_modal" tabindex="-1" role="dialog" aria-hidden="true">
  88.                 <div class="modal-dialog" role="document">
  89.                         <form action="save_query.php" method="POST" enctype="multipart/form-data">
  90.                                 <div class="modal-content">
  91.                                         <div class="modal-body">
  92.                                                 <div class="col-md-2"></div>
  93.                                                 <div class="col-md-8">
  94.                                                         <div class="form-group">
  95.                                                                 <label>Product Name</label>
  96.                                                                 <input class="form-control" type="text" name="product_name">
  97.                                                         </div>
  98.                                                         <div class="form-group">
  99.                                                                 <label>Product Price</label>
  100.                                                                 <input class="form-control" type="number" name="product_price">
  101.                                                         </div>
  102.                                                         <div class="form-group">
  103.                                                                 <label>Product Photo</label>
  104.                                                                 <input class="form-control" type="file" name="product_image">
  105.                                                         </div>
  106.                                                 </div>
  107.                                         </div>
  108.                                         <div style="clear:both;"></div>
  109.                                         <div class="modal-footer">
  110.                                                 <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  111.                                                 <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  112.                                         </div>
  113.                                 </div>
  114.                         </form>
  115.                 </div>
  116.         </div>
  117. </body>
  118. <script src="js/jquery-3.2.1.min.js"></script>
  119. <script src="js/bootstrap.js"></script>
  120. </html>
purchase.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <meta charset="URF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-3"></div>
  14.         <div class="col-md-6 well">
  15.                 <h3 class="text-primary">PHP - Simple Shopping Cart</h3>
  16.                 <hr style="border-top:1px dotted #ccc;"/>
  17.                 <center><h1>Thank you for Shopping!</h1></center>
  18.                 <center><a href="session.php">Back to prdouct</a></center>
  19.         </div>
  20.  
  21. </body>
  22. </html>

Creating PHP Query

This code contains the php query of the application. This code will sent the data inputs to the database server. To do that just copy and write this block of codes inside the text editor, then save it as save_query.php.
  1. <?php
  2.         require_once 'conn.php';
  3.  
  4.         if(ISSET($_POST['save'])){
  5.                 if(!empty($_POST['product_name']) && !empty($_POST['product_price'])){
  6.                         $product_name = addslashes($_POST['product_name']);
  7.                         $product_price = $_POST['product_price'];
  8.  
  9.                         $file = explode(".", $_FILES['product_image']['name']);
  10.                         $ext = array("png", "gif", "jpg", "jpeg");
  11.  
  12.                         if(in_array($file[1], $ext)){
  13.                                 $file_name = $file[0].'.'.$file[1];
  14.                                 $tmp_file = $_FILES['product_image']['tmp_name'];
  15.                                 $location = "upload/".$file_name;
  16.                                 $new_location = addslashes($location);
  17.  
  18.                                 if(move_uploaded_file($tmp_file, $location)){
  19.                                         $conn->query("INSERT INTO `product` VALUES('', '$product_name', '$product_price', '$new_location')");
  20.                                         echo "<script>alert('Data Insert')</script>";
  21.                                         echo "<script>window.location = 'index.php'</script>";
  22.                                 }
  23.  
  24.                         }else{
  25.                                 echo "<script>alert('File not available')</script>";
  26.                                 echo "<script>window.location = 'index.php'</script>";
  27.                         }
  28.  
  29.                 }else{
  30.                         echo "<script>alert('Please complete the required field!')</script>";
  31.                 }
  32.  
  33.  
  34.         }
  35. ?>

Creating Shopping Cart

This code contains the main function of the application. This code will store the database data to the PHP session, to be able to manipulate as an array. To do that just copy and write this block of codes inside the text editor, then save it as shown below. addcart.php
  1. <?php
  2.         session_start();
  3.  
  4.         if(ISSET($_POST['add'])){
  5.                 if(ISSET($_SESSION['cart'])){
  6.                         $product_array_id = array_column($_SESSION["cart"], "item_id");
  7.                         if(!in_array($_GET['id'], $product_array_id)){
  8.                                 $count = count($_SESSION['cart']);
  9.                                 $product_array = array(
  10.                                         'product_id'            =>      $_GET['id'],
  11.                                         'product_name'          =>      $_POST['product_name'],
  12.                                         'product_price' =>      $_POST['product_price'],
  13.                                         'qty'                   =>      $_POST['qty']
  14.                                 );
  15.                                 $_SESSION['cart'][$count] = $product_array;
  16.                                 echo "<script>window.location = 'index.php'</script>";
  17.                         }else{
  18.                                 echo "<script>window.location = 'index.php'</script>";
  19.                         }
  20.                 }else{
  21.                         $product_array = array(
  22.                                 'product_id'            =>      $_GET['id'],
  23.                                 'product_name'          =>      $_POST['product_name'],
  24.                                 'product_price' =>      $_POST['product_price'],
  25.                                 'qty'                   =>      $_POST['qty']
  26.                         );
  27.                         $_SESSION['cart'][0] = $product_array;
  28.                        
  29.                         echo "<script>window.location = 'index.php'</script>";
  30.                 }
  31.         }
  32. ?>
delete.php
  1. <?php
  2.         session_start();
  3.         if(ISSET($_GET['id'])){
  4.                 foreach($_SESSION['cart'] as $keys => $values){
  5.                         if($values['product_id'] == $_GET['id']){
  6.                                 unset($_SESSION['cart'][$keys]);
  7.                                 echo "<script>alert('Product Remove')</script>";
  8.                                 echo "<script>window.location = 'index.php'</script>";
  9.                         }
  10.                 }
  11.         }
  12. ?>
session.php
  1. <?php
  2.         session_start();
  3.         session_destroy();
  4.         header('location: index.php');
  5. ?>
There you have it we successfully created a Simple Shopping Cart using PHP. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!

Add new comment