Build Simple Shopping Cart using PHP, Ajax and MySQL
In online marketing, a shopping cart is a piece of software that facilitates the purchase of a products. So if you want to build a simple PHP shopping cart in your web project, then you’re here at right place. The shopping cart functionality handled with PHP SESSION to add remove products.
In this tutorial, you will learn how to create a Simple Shopping Cart using PHP with MySQL.This is a very simple script, you can copy paste and modify according to your requirement.
Before started to Build Simple Shopping Cart using PHP, Ajax and MySQL, look files structure:
- build-simple-shopping-cart-using-php-ajax
- class
- DBConnection.php
- Cart.php
- css
- style.css
- images
- templates
- header.php
- footer.php
- index.php
- add.php
- cart.php
- remove.php
- class
Steps 1: Create MySQL Database Table
So lets start creating a simple Shopping Cart using PHP, Ajax and MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
-- Table structure for table `products` CREATE TABLE `products` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `sku` varchar(255) NOT NULL, `image` text NOT NULL, `price` double(10,2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Dumping data for table `products` INSERT INTO `products` (`id`, `name`, `sku`, `image`, `price`) VALUES (1, 'Product 1', 'PROD01', 'images/1.jpg', 100.00), (2, 'Product 2', 'PROD02', 'images/2.jpg', 200.00), (3, 'Product 3', 'PROD03', 'images/3.jpg', 300.00), (4, 'Product 4', 'PROD04', 'images/4.jpg', 400.00), (5, 'Product 5', 'PROD05', 'images/5.jpg', 500.00), (6, 'Product 6', 'PROD06', 'images/6.jpg', 600.00), (7, 'Product 7', 'PROD07', 'images/7.jpg', 700.00), (8, 'Product 8', 'PROD08', 'images/8.jpg', 800.00); -- Indexes for table `products` ALTER TABLE `products` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `product_code` (`sku`); -- AUTO_INCREMENT for table `products` ALTER TABLE `products` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; |
Step 2: Connect to Database file named DBConnection.php
The code below shows the database credentials
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * @package PHP Cart(DBConnection) * * @author TechArise Team * * @email info@techarise.com * */ // Database Connection class DBConnection { private $_dbHostname = "localhost"; private $_dbName = "demo_DB"; private $_dbUsername = "root"; private $_dbPassword = ""; private $_con; public function __construct() { try { $this->_con = new PDO("mysql:host=$this->_dbHostname;dbname=$this->_dbName", $this->_dbUsername, $this->_dbPassword); $this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } // return Connection public function returnConnection() { return $this->_con; } } ?> |
Step 3: Create class
Create a class file named
Cart.php
inside class/ folder.- The Cart class handles the Cart process
__construct()
— Loads the required DBConnection.getAllProduct()
— get all Product.getProduct()
— get single Record.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<?php /** * @package Cart class * * @author TechArise Team * * @email info@techarise.com * */ include("DBConnection.php"); class Cart { protected $db; private $_sku; public function setSKU($sku) { $this->_sku = $sku; } public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // getAll Product public function getAllProduct() { try { $sql = "SELECT * FROM products"; $stmt = $this->db->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } // get Student public function getProduct() { try { $sql = "SELECT * FROM products WHERE sku=:sku"; $stmt = $this->db->prepare($sql); $data = [ 'sku' => $this->_sku ]; $stmt->execute($data); $result = $stmt->fetch(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } } ?> |
Steps 4: List Products in Shop
In index.php, we will get products details from MySQL database table shop_products and list products in shop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?php session_start(); include('class/Cart.php'); $cart = new Cart(); $product_array = $cart->getAllProduct(); include('templates/header.php'); if(!empty($_SESSION["cart_item"])){ $count = count($_SESSION["cart_item"]); } else { $count = 0; } ?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Build Simple Shopping Cart using PHP <a style="float: right;" href="cart.php" class="btn btn-primary text-right"> Cart <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-light" id="cart-count"><?php print $count; ?></span></a></h2> </div> <div class="row"> <div class="col" id="add-item-bag" style="width:100%;"></div> <div id="product-grid"> <?php if (!empty($product_array)) { foreach($product_array as $key=>$value){ ?> <div class="product-item"> <div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div> <div class="product-tile-footer"> <div class="product-title"><?php echo $product_array[$key]["name"]; ?></div> <div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div> <div class="cart-action"> <input type="text" class="product-quantity" id="qty-<?php echo $product_array[$key]["id"]; ?>" name="quantity" value="1" size="2" /> <button type="button" class="btnAddAction" data-itemid="<?php echo $product_array[$key]["id"]; ?>" id="product-<?php echo $product_array[$key]["id"]; ?>" data-action="action" data-sku="<?php echo $product_array[$key]["sku"]; ?>" data-proname="<?php echo $product_array[$key]["sku"]; ?>"> Add to Cart</button> </div> </div> </div> <?php } } ?> </div> </div> </div> </section> <?php include('templates/footer.php');?> <script type="text/javascript"> jQuery(document).on('click', 'button.btnAddAction', function() { var item_id = jQuery(this).data('itemid'); var qty = jQuery('#qty-'+item_id).val(); var sku = jQuery(this).data('sku'); var product_name = jQuery(this).data('proname'); jQuery.ajax({ type:'POST', url:'add.php', data:{product_id:item_id, quantity:qty, sku:sku}, dataType:'json', beforeSend: function () { jQuery('button#product-'+item_id).button('loading'); }, complete: function () { jQuery('button#product-'+item_id).button('reset'); }, success: function (json) { jQuery('#cart-count').html(json.count); jQuery("#add-item-bag").html('<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button><strong>Success!</strong> You have added <strong>'+product_name+'</strong> to your shopping cart!</div>'); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Steps 5: Add Products to Cart(Manage Cart with PHP SESSION)
create file named a add.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php session_start(); $json = array(); include('class/Cart.php'); $cart = new Cart(); $cart->setSKU($_POST["sku"]); $productByCode = $cart->getProduct(); if(!empty($_POST["quantity"])) { $itemArray = array($productByCode["sku"]=>array('name'=>$productByCode["name"], 'sku'=>$productByCode["sku"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"], 'image'=>$productByCode["image"])); if(!empty($_SESSION["cart_item"])) { if(in_array($productByCode["sku"],array_keys($_SESSION["cart_item"]))) { foreach($_SESSION["cart_item"] as $k => $v) { if($productByCode["sku"] == $k) { if(empty($_SESSION["cart_item"][$k]["quantity"])) { $_SESSION["cart_item"][$k]["quantity"] = 0; } $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; } } } else { $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); } } else { $_SESSION["cart_item"] = $itemArray; } $json['count'] = count($_SESSION["cart_item"]); } header('Content-Type: application/json'); echo json_encode($json); ?> |
Make Ajax Request: add product in cart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<script type="text/javascript"> jQuery(document).on('click', 'button.btnAddAction', function() { var item_id = jQuery(this).data('itemid'); var qty = jQuery('#qty-'+item_id).val(); var sku = jQuery(this).data('sku'); var product_name = jQuery(this).data('proname'); jQuery.ajax({ type:'POST', url:'add.php', data:{product_id:item_id, quantity:qty, sku:sku}, dataType:'json', beforeSend: function () { jQuery('button#product-'+item_id).button('loading'); }, complete: function () { jQuery('button#product-'+item_id).button('reset'); }, success: function (json) { jQuery('#cart-count').html(json.count); jQuery("#add-item-bag").html('<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">×</button><strong>Success!</strong> You have added <strong>'+product_name+'</strong> to your shopping cart!</div>'); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Step 6: View cart details
In cart.php we will handle functionality to display cart details like Product Name, SKU, Quantity, Unit Price, Price, total etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
<?php session_start(); include('templates/header.php'); if(!empty($_SESSION["cart_item"])){ $count = count($_SESSION["cart_item"]); } else { $count = 0; } ?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Build Simple Shopping Cart using PHP <a style="float: right;" href="#" class="btn btn-primary text-right"> Cart <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-light" id="cart-count"><?php print $count; ?></span></a></h2> </div> <div class="row"> <div id="shopping-cart"> <?php if(isset($_SESSION["cart_item"])){ $total_quantity = 0; $total_price = 0; ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <thead> <tr> <th style="text-align:left;">Name</th> <th style="text-align:left;">SKU</th> <th style="text-align:right;" width="5%">Quantity</th> <th style="text-align:right;" width="10%">Unit Price</th> <th style="text-align:right;" width="10%">Price</th> <th style="text-align:center;" width="5%">Remove</th> </tr> </thead> <tbody id="render-cart-data"> <?php foreach ($_SESSION["cart_item"] as $item){ $item_price = $item["quantity"]*$item["price"]; ?> <tr id="<?php echo $item["sku"]; ?>"> <td><img src="<?php echo $item["image"]; ?>" class="cart-item-image" /><?php echo $item["name"]; ?></td> <td><?php echo $item["sku"]; ?></td> <td style="text-align:right;"><?php echo $item["quantity"]; ?></td> <td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td> <td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td> <td style="text-align:center;"><a data-sku="<?php echo $item["sku"]; ?>" class="text-danger btnRemoveAction"><i class="fa fa-times" aria-hidden="true"></i></a></td> </tr> <?php $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } ?> <tr> <td colspan="2" align="right">Total:</td> <td align="right" id="render-qty"><?php echo $total_quantity; ?></td> <td align="right" colspan="2" id="render-total"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td> <td></td> </tr> </tbody> <tfoot> <tr> <td colspan="2"><a href="index.php" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td> <td ></td> <td colspan="3"></td> </tr> </tfoot> </table> <?php } else { ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <tfoot> <tr> <td colspan="4"><div class="no-records">Your Cart is Empty</div></td> </tr> <tr> <td colspan="2"><a href="index.php" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td> <td></td> <td></td> </tr> </tfoot> </table> <?php } ?> </div> </div> </div> </section> <?php include('templates/footer.php');?> <script type="text/javascript"> jQuery(document).on('click', 'a.btnRemoveAction', function() { var sku = jQuery(this).data('sku'); jQuery.ajax({ type:'POST', url:'remove.php', data:{sku:sku}, dataType:'json', success: function (json) { if(json.total_quantity) { jQuery('#cart-count').html(json.count); jQuery('#render-qty').html(json.total_quantity); jQuery('#render-total').html("$ "+json.total_price); jQuery("#"+sku).empty(); } else { jQuery('#render-cart-data').empty(); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Steps 7: Remove Product from Cart(Manage Cart with PHP SESSION)
create file named a remove.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php session_start(); $json = array(); $total_quantity = 0; $total_price = 0; $count = 0; if(!empty($_SESSION["cart_item"]) && count($_SESSION["cart_item"])>0) { if(!empty($_SESSION["cart_item"])) { foreach($_SESSION["cart_item"] as $k => $v) { if($_POST["sku"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } $bindHTML = ''; foreach ($_SESSION["cart_item"] as $item){ $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } $count = count($_SESSION["cart_item"]); $json['total_quantity'] = $total_quantity; $json['total_price'] = number_format($total_price, 2); $json['count'] = $count; } header('Content-Type: application/json'); echo json_encode($json); ?> |
Make Ajax Request: remove product from cart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<script type="text/javascript"> jQuery(document).on('click', 'a.btnRemoveAction', function() { var sku = jQuery(this).data('sku'); jQuery.ajax({ type:'POST', url:'remove.php', data:{sku:sku}, dataType:'json', success: function (json) { if(json.total_quantity) { jQuery('#cart-count').html(json.count); jQuery('#render-qty').html(json.total_quantity); jQuery('#render-total').html("$ "+json.total_price); jQuery("#"+sku).empty(); } else { jQuery('#render-cart-data').empty(); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); </script> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Integrate CCAvenue Payment Gateway using PHP | Tech Arise</title> <link rel="icon" type="image/ico" href="https://techarise.com/wp-content/themes/v1/favicon.ico"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </body> </html> |