Shopping Cart With PHP and jQuery

Online store is now more popular than offline stores, this is caused by people who really want to spend more time at home, easier to shop online effortlessly search for the desired product, just search on searchable columns and meet, different from shopping shop Offline is arguably very difficult to find what we need because out of stores and into other stores just to find one type of product only.

With shopping on the online store can save time because enough at home and purchased products will be sent via a delivery service provided by the online store. Online stores can be accessed as long as our home connected with internet and requires devices such as computers, smartphones, tablets and others.

In this tutorial will be discussed how to create shopping cart by using jquery, ajax, jquery.mycart and php, jquery.mycart.js can be found at For an explanation of how to create a shopping cart using jquery and php as below.

Creating Database
This database is to store product data, user data and temporary purchase data after checkout. Create a new database with the name of the cart and three tables with the name of each table is, product, shopping, and user or you can use the sql code below

USE `cart`;

CREATE TABLE `product` (
  `name` varchar(80) NOT NULL,
  `summary` varchar(255) NOT NULL,
  `price` double NOT NULL,
  `quantity` varchar(10) NOT NULL,
  `image` varchar(100) NOT NULL

CREATE TABLE `shopping` (
  `id_user` int(2) NOT NULL PRIMARY KEY,
  `id` int(11) NOT NULL PRIMARY KEY,
  `amount_quantity` varchar(10) NOT NULL,
  `amount_price` double NOT NULL,
  `order_number` int(7) NOT NULL

  `id_user` int(2) NOT NULL PRIMARY KEY,
  `name_user` varchar(45) NOT NULL

Connect to Database

Connecting to the database using php pdo and mysql database, how to connect to the mysql database using php as below.

try {
    $host = 'localhost';
    $dbnm = 'cart';
    $user = 'root';
    $pass = '';
    $dbh = new PDO('mysql:host='.$host.';dbname='.$dbnm, $user, $pass);
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";

Library for Shopping Cart

This library is for layout design and for shopping carts, for libraries still using the framework from Bootstrap, Awesome Fonts, jQuery and jQuery MyCart, these frameworks to support this shopping cart creation. For the code to call the framework library is as below.

<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
            top: -10px;
            right: 10px;
        .my-cart-icon-affix {
            position: fixed;
            z-index: 999;

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.mycart.min.js"></script>

View Products

View products to display products that have been stored into the database along with two buttons to see product details and for shopping, if the detail button is pressed it will display a modal dialog that will display complete info about the product, but if the shopping button is pressed means he has been shopping products And must check out for legitimate shopping.

include "config.php";
<nav class="navbar navbar-default navbar-static-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">
            <h2 style="margin-top:0;">Products</h2>
        <p class="navbar-text navbar-right"><i class="fa fa-shopping-cart fa-2x my-cart-icon"><span class="badge badge-notify my-cart-badge"></span></i></p>
        <p class="navbar-text navbar-right"><i class="fa fa-user fa-2x"></i> <a href="#" class="navbar-link">Tedir Ghazali</a></p>
        <p class="navbar-text navbar-right"><a href="order.php" class="navbar-link"><i class="fa fa-envelope fa-2x"></i></a></p>
<div class="container">
        <div class="row">
        $stmt = $dbh->prepare("SELECT * FROM product");
        if ($stmt->execute()) {
            while ($row = $stmt->fetch()) {
          <div class="col-sm-3 col-md-3">
            <div class="thumbnail">
              <img src="assets/images/<?php echo $row['image'] ?>" alt="<?php echo $row['name'] ?>" style="height:150px;width:100%;">
              <div class="caption text-center">
                <h3><?php echo $row['name'] ?></h3>
                <p><strong>Price</strong>: $<?php echo $row['price'] ?><br/><?php echo $row['summary'] ?></p>
                    <button type="button" class="btn btn-danger my-cart-btn" data-id="<?php echo $row['id'] ?>" data-name="<?php echo $row['name'] ?>" data-summary="<?php echo $row['summary'] ?>" data-price="<?php echo $row['price'] ?>" data-quantity="<?php echo $row['quantity'] ?>" data-image="assets/images/<?php echo $row['image'] ?>">Add to Cart</button> 
                    <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal-<?php echo $row['id'] ?>">Details</button>
            <!-- Modal -->
            <div class="modal fade" id="myModal-<?php echo $row['id'] ?>" tabindex="-<?php echo $row['id'] ?>" role="dialog" aria-labelledby="myModalLabel-<?php echo $row['id'] ?>">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel-<?php echo $row['id'] ?>"><?php echo $row['name'] ?></h4>
                  <div class="modal-body">
                    <img src="assets/images/<?php echo $row['image'] ?>" style="width:100%"/><br/>
                    <strong>Price</strong>: $<?php echo $row['price'] ?><br/>
                    <?php echo $row['summary'] ?>

jQuery Code for Shopping Cart

jQuery function is to run the shopping cart function so that when the shopping button is pressed it will automatically enter into an icon on the navbar with numbers or quantities purchased on one or more products, if the icon on the navbar is clicked it will appear modal dialog containing the product Purchased and checkout button. For syntax code as below.

$(function () {

    var goToCartIcon = function($addTocartBtn){
      var $cartIcon = $(".my-cart-icon");
      var $image = $('<img width="30px" height="30px" src="' + $"image") + '"/>').css({"position": "fixed", "z-index": "999"});
      var position = $cartIcon.position();
        left: position.left
      }, 500 , "linear", function() {

      currencySymbol: '$',
      classCartIcon: 'my-cart-icon',
      classCartBadge: 'my-cart-badge',
      classProductQuantity: 'my-product-quantity',
      classProductRemove: 'my-product-remove',
      classCheckoutCart: 'my-cart-checkout',
      affixCartIcon: true,
      showCheckoutModal: true,
      /*cartItems: [
        {id: 1, name: 'Juice Blender', summary: 'Bisa blender jus, bumbu masakan', price: 10, quantity: 1, image: 'assets/images/img_1.png'},
        {id: 2, name: 'TV remote', summary: 'Bisa untuk semua tv', price: 20, quantity: 2, image: 'assets/images/img_2.png'},
        {id: 3, name: 'Sony camera', summary: 'Kamera murah', price: 30, quantity: 1, image: 'assets/images/img_3.png'}
      clickOnAddToCart: function($addTocart){
      afterAddOnCart: function(products, totalPrice, totalQuantity) {
        console.log("afterAddOnCart", products, totalPrice, totalQuantity);
      clickOnCartIcon: function($cartIcon, products, totalPrice, totalQuantity) {
        console.log("cart icon clicked", $cartIcon, products, totalPrice, totalQuantity);
      checkoutCart: function(products, totalPrice, totalQuantity) {
        var checkoutString = "Total Price: " + totalPrice + "\nTotal Quantity: " + totalQuantity;
        $.each(products, function(){
            shoppingcart(, this.quantity, this.price * this.quantity);
        console.log("checking out", products, totalPrice, totalQuantity);
      getDiscountPrice: function(products, totalPrice, totalQuantity) {
        console.log("calculating discount", products, totalPrice, totalQuantity);
        return totalPrice * 0.99;


Save Order After Checkout

Store the product into the database after the checkout button is clicked like the syntax code below.

$user = $_POST['ui'];
$idpro = $_POST['id'];
$aq = $_POST['aq'];
$ap = $_POST['ap'];
$order = $_POST['order'];
$stmt = $dbh->prepare("INSERT INTO shopping VALUES (?,?,?,?,?)");
$stmt->bindParam(1, $user);
$stmt->bindParam(2, $idpro);
$stmt->bindParam(3, $aq);
$stmt->bindParam(4, $ap);
$stmt->bindParam(5, $order);

The above code is a data transfer from jquery ajax to add data as below.

$angka = substr(uniqid(rand(), true), 7, 7);
$order = preg_replace("/[^0-9]/", "",$angka);

function shoppingcart(allid,allquantity,allprice){
    var myorder = "<?php echo $order ?>";
    $.post('order.php',{ui:'1', id:allid, aq:allquantity, ap:allprice, shopping:'shopping', order:myorder});

View Order Product

View order product is a new page to display the order of products that have been purchased by the user, View order product is only displayed by user, so here do not use user login so the user only one with id is 1, In the order product view page there are products that have been purchased and will be displayed into the table the total price along with the discount, and in the page there is a button to cancel the order.

<div class="container">
        <h1>Tedir Ghazali</h1>
        <table class="table table-bordered">
                $stmt = $dbh->prepare("SELECT * FROM shopping a, product b where and a.id_user = 1");
                if ($stmt->execute()) {
                  while ($row = $stmt->fetch()) {
                    <td width="120"><img src="assets/images/<?php echo $row['image'] ?>" style="width:100px"/></td>
                    <td><strong><?php echo $row['name'] ?></strong></td>
                    <td width="80"><?php echo $row['amount_quantity'] ?></td>
                    <td width="80"><?php echo $row['amount_price'] ?></td>
                $stmt2 = $dbh->prepare("SELECT sum(amount_price) as ap2 FROM shopping where id_user = 1");
                $row2 = $stmt2->fetch();
                    <th colspan="2">Total</th>
                    <th colspan="2"><?php echo $row2['ap2'] ?></th>
                    <th colspan="2">Total (including discount)</th>
                    <th colspan="2"><?php echo $row2['ap2']*0.99 ?></th>
        <p class="text-right"><a href="index.php" class="btn btn-default">Back to homepage</a> <a href="?del=1" class="btn btn-danger">Cancel</a></p>


Leave a Reply

Your email address will not be published. Required fields are marked *