Ajax Shopping Cart PHP MYSQLi Tutorial With Example demo

Ajax Shopping Cart PHP MYSQLi Tutorial With Example

Today, We want to share with you Ajax Shopping Cart PHP MYSQLi Tutorial With Example.In this post we will show you Shopping Cart with Ajax, PHP and MySQLi, hear for PHP Shopping Cart Tutorial Using SESSIONS we will give you demo and example for implement.In this post, we will learn about An AJAX Based Shopping Cart with PHP, CSS & jQuery with an example.

Ajax Shopping Cart PHP MYSQLi Tutorial With Example

There are the Following The simple About Ajax Shopping Cart PHP MYSQLi Tutorial With Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop Ajax Shopping Cart with PHP and jQuery, so the Shopping Cart with jQuery, Ajax and PHP for this example is following below.

Step 1 : Configuration of the DATABASE

Items TABLE

simple ecommerce shopping cart php mysql for Items TABLE

CREATE TABLE `items` (
`item_id` int(11) NOT NULL,
`item_name` varchar(255) NOT NULL,
`item_image` varchar(255) DEFAULT NULL,
`item_description` text,
`item_price` decimal(10,2) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `items`
ADD PRIMARY KEY (`item_id`),
ADD KEY `name` (`item_name`);

ALTER TABLE `items`
MODIFY `item_id` int(11) NOT NULL AUTO_INCREMENT;

ORDERS TABLES

CREATE TABLE `customer_orders` (
`order_id` int(11) NOT NULL,
`order_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fname_user_order` varchar(255) NOT NULL,
`email_user_order` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `customer_orders`
ADD PRIMARY KEY (`order_id`),
ADD KEY `name` (`fname_user_order`),
ADD KEY `email` (`email_user_order`),
ADD KEY `order_date` (`order_date`);

ALTER TABLE `customer_orders`
MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT;

ORDER ITEMS TABLES

CREATE TABLE `customer_orders_items` (
`order_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`item_qty` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `customer_orders_items`
ADD PRIMARY KEY (`order_id`,`item_id`);

Master Data of PRODUCTS AND IMAGES

INSERT INTO `items` (`item_id`, `item_name`, `item_image`, `item_description`, `item_price`) VALUES
(1, 'mobile', 'car.jpg', 'It\'s a car. Batteries not included, not required. Powered by Jaydeep.', '6000.00'),
(2, 'Banana Bear', 'spaicy-drags.jpg', 'Beware. perfect drags is extremely spaicy.', '8.00'),
(3, 'eags', 'fish.jpg', 'There is something fishy going on here...', '7.50'),
(4, 'buttor Gorilla', 'gorilla.jpg', 'Unlike the spaicy drags, this one is chill.', '8.80'),
(5, 'dove Duck', 'rubber-duck.jpg', 'Best partner in the bath tub.', '9.75'),
(6, 'sperrow perfect', 'rubiks-perfect.jpg', 'others say that this perfect trains simple intelligence. data others claim that it\'s just frustration.', '9.30');

Ajax Shopping Cart PHP MYSQLi Tutorial With Example card - Ajax Shopping Cart PHP MYSQLi Tutorial With Example
Ajax Shopping Cart PHP MYSQLi Tutorial With Example card

Ajax Shopping Cart PHP MYSQLi Tutorial With Example Step By Step

Step 2: Setup DATABASE Config and PRODUCT

config.php

All The PRODUCTS FROM THE MYSQL DATABASE

index.php

 PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES => false
  ]
);

$stmt = $pdo->query('SELECT * FROM `items`');
while ($row = $stmt->fetch()){ print_r($row); }
?>

index.php



  <title>An AJAX Based Shopping Cart with PHP, CSS & jQuery</title>
  
  
  

  
  
  
  


  

  
  header.container{ background:#f2c5f9; }
  footer.container{ background:#eaeaea; }
  header.container, footer.container{ padding:20px; }
  #items img{ max-width:100%; }
  #alert, #cart{ display:none; }
  



	<h1>Simple PHP MySQLi Shopping Cart using jquery AJAX</h1>
  <div class="alert alert-success" id="alert"></div>


  <header class="container"><div class="row"><div class="col">
    My Awesome Site <span>[mobilet]</span>
  </div></div></header>


  <div id="items" class="container"><div class="row">query('SELECT * FROM `items`');
    while ($row = $stmt->fetch()){ ?>
      <div class="col-4">
        <img src="images/"/>
        <h3></h3>
        <div>$</div>
        <div></div>
        <div class="btn btn-success" onclick="addTomobilet();">Add to cart</div>
      </div>
      <?php

      $now++;
      if ($now==3) {
        echo '</div><div class="row">';
        $now = 0;
      }
  } ?></div></div>


  <div class="container pakainfo"><div class=" pakainforow"><div class="col" id="cart"></div></div>


  <footer class="pakainfo container"><div class="row"><div class="col">
    © Copyright pakainfo.com. All rights reserved.
  </div></div></footer>


Step 3 : CART ACTIONS(USER SIDE AND SERVER SIDE)

live-item-ajax-cart.php(ADD TO CART – PHP BASED SERVER SIDE)

 PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES => false,
  ]
);
 
switch ($_POST['request']) {
  case "add":
  if (is_numeric($_SESSION['cart'][$_POST['item_id']])) {
    $_SESSION['cart'][$_POST['item_id']]++;
  } else {
    $_SESSION['cart'][$_POST['item_id']] = 1;
  }
  break;
}
?>

ADD TO CART – USER SIDE

cart.js

function hideMessage(){
  $('#alert').hide().html("");
}

function addTomobilet(id){
  $.ajax({
    url: "live-item-ajax-cart.php",
    method: "POST",
    data: { 
      item_id:id,
      request:"add"
    }
  }).done(function(msg) {
    $('#alert').html("Item added").show();
    setTimeout(hideMessage, 2000);
  });
}

Display CART – PHP BASED SERVER SIDE

live-item-ajax-cart.php

switch ($_POST['request']) {
  case "show":
  $stmt = $pdo->query('SELECT * FROM `items`');
  $items = array();
  while ($row = $stmt->fetch()){
    $items[$row['item_id']] = $row;
  }

  $sub = 0;
  $total = 0; ?>
  <h1>MY CART</h1>
  <table class="table table-striped">
    <tr>
      <th>Qty</th>
      <th>Item</th>
      <th>Price</th>
    </tr>
    $qty) {
      $sub = $qty * $items[$id]['item_price'];
      $total += $sub;

      printf("<tr><td></td><td>%s</td><td>$%0.2f</td></tr>",
        $id, $id, $qty,
        $items[$id]['item_name'],
        $sub
      );
    }
    ?>
    <tr>
      <td></td>
      <td><strong>Grand Total</strong></td>
      <td><strong>$</strong></td>
    </tr>
    0){ ?>
    <tr>
      <td colspan="2"></td>
      <td>
        Name: <br><br>
        Email: <br><br>
        
      </td>
    </tr>
    
  </table>
  <?php
  break;
}

Display CART – USER SIDE

cart.js

function togglemobilet(){
  var cart = $('#cart'),
  items = $('#items');

  if (cart.is(":visible")) {
    cart.hide();
    items.show();
  }
  else {
    $.ajax({
      url: "live-item-ajax-cart.php",
      method: "POST",
      dataType: "html",
      data: { 
        request:"show"
      }
    }).done(function(res) {
      items.hide();
      cart.html(res).show();
    });
  }
}

CHANGE QUANTITY – PHP BASED ON SERVER SIDE

live-item-ajax-cart.php

//Ajax Shopping Cart PHP MYSQLi Tutorial With Example
case "qty":
  if ($_POST['qty']==0) {
    unset($_SESSION['cart'][$_POST['item_id']]);
  } else {
    $_SESSION['cart'][$_POST['item_id']] = $_POST['qty'];
  }
break;

CHANGE QUANTITY – USER SIDE

function qtymobilet(id){
  var qty = parseInt($('#qty_'+id).val());
  if ($.isNumeric(qty)) {
    $.ajax({
      url: "live-item-ajax-cart.php",
      method: "POST",
      data: { 
        request:"qty",
        item_id:id,
        qty:qty
      }
    }).done(function(res) {
      $('#alert').html("Item Quantity changed").show();
      setTimeout(hideMessage, 2000);
      $('#cart').hide();
      togglemobilet();
    });
  } else {
    alert("Please enter a valid correct number or Try again!");
  }
}

Step 4 : ORDER CHECKOUT(SERVER SIDE and USER SIDE)

(CHECKOUT – PHP BASED ON SERVER SIDE)live-item-ajax-cart.php

case "checkout":

  $sql = sprintf("INSERT INTO `customer_orders` (`fname_user_order`, `email_user_order`) VALUES ('%s', '%s')", 
    $_POST['name'], $_POST['email']
  );
  $pdo->exec($sql);
  $get_id_last = $pdo->lastInsertId();


  $sql = "INSERT INTO `customer_orders_items` (`order_id`, `item_id`, `item_qty`) VALUES ";
  foreach ($_SESSION['cart'] as $id=>$qty) {
    $sql .= sprintf("(%u,%u,%u),", $get_id_last, $id, $qty);
  }
  $sql = substr($sql,0,-1);
  $sql .= ";";
  $pdo->exec($sql);

  $_SESSION['cart'] = array();
  break;

CHECKOUT – CLIENT SIDE

Jquery CSS in CHECKOUT – USER SIDE

function liveAjaxmobiletCheckout(){
  var name = $('#user_fname').val(),
  email = $('#user_email').val(),
  resError = "";

  if (name=="") { resError += "Please enter your name\n"; }
  if (email=="") { resError += "Please enter your email\n"; }
  if (resError=="") {
    $.ajax({
      url: "live-item-ajax-cart.php",
      method: "POST",
      data: { 
        request : "checkout",
        name : name,
        email : email
      }
    }).done(function(res) {
      $('#cart').html("Good Luck, THANK YOU! We have received your order Successfully");
    });
  } else {
    alert(resError);
  }
}

Angular 6 CRUD Operations Application Tutorials

Read :

  Simple PHP Shopping Cart

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Ajax Shopping Cart PHP MYSQLi Tutorial With Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

avatar
  Subscribe  
Notify of