Menu

Build Shopping Cart with Ajax, PHP and MySQL

Build Shopping Cart with Ajax, PHP and MySQL

Shopping cart is a part of eCommerce project in which multiple products are added and viewed added product details like price, total amount, taxes etc. before submitting order. So if you're thinking about creating shopping cart in your web project, then you're here at right place. In this tutorial you will learn how to create shopping cart with Ajax, PHP and MySQL. The shopping cart functionality handled with PHP SESSION to add remove products. The tutorial explained in easy steps with live demo to understand cart functionality. You can also download source code of live to build your shopping cart from scratch.



As we have covered this tutorial with live demo to build shopping cart with Ajax, PHP and MySQL, so the file structure for this example is following.


  • index.php

  • cart.js

  • manage_cart.php

  • view_cart.php

  • checkout.php

  • success.php



Steps1: Create MySQL Database Table
First we will create MySQL database table shop_products and insert products in this table to display products in shop to add into cart.
CREATE TABLE `shop_products` (
`id` int(11) NOT NULL,
`product_name` varchar(60) NOT NULL,
`product_desc` text NOT NULL,
`product_code` varchar(60) NOT NULL,
`product_image` varchar(60) NOT NULL,
`product_price` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Steps2: List Products in Shop
In index.php, we will get products details from MySQL database table shop_products and list products in shop.
<div class="col-md-8 text-center">
<ul class="products-container">
<?php
$sql_query = "SELECT product_name, product_desc, product_code, product_image, product_price FROM shop_products";
$resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
while( $row = mysqli_fetch_assoc($resultset) ) {
?>
<li>
<form class="product-form">
<h4><?php echo $row["product_name"]; ?></h4>
<div><img class="product_image" src="images/<?php echo $row["product_image"]; ?>"></div>
<div>Price : <?php echo $currency; echo $row["product_price"]; ?></div>
<div class="product-box">
<div>
Color :
<select name="product_color">
<option value="Black">Black</option>
<option value="Gold">Gold</option>
<option value="White">White</option>
</select>
</div>
<div>
Qty :
<select name="product_qty">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<input name="product_code" type="hidden" value="<?php echo $row["product_code"]; ?>">
<button type="submit">Add to Cart</button>
</div>
</form>
</li>
<?php } ?>
</ul>
</div>


Steps3: Add Products to Cart
Now in cart.js, we will handle functionality to add products to cart with Ajax request to manage_cart.php.
$(".product-form").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...');
$.ajax({
url: "manage_cart.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
$("#cart-container").html(data.products);
button_content.html('Add to Cart');
})
e.preventDefault();
});


Steps4: Manage Cart with PHP SESSION
In manage_cart.php, we will manage cart to add products in cart. If there are already product in cart then we will increment quantity of that product.
if(isset($_POST["product_code"])) {
foreach($_POST as $key => $value){
$product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
$statement = $conn->prepare("SELECT product_name, product_price FROM shop_products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price);
while($statement->fetch()){
$product["product_name"] = $product_name;
$product["product_price"] = $product_price;
if(isset($_SESSION["products"])){
if(isset($_SESSION["products"][$product['product_code']])) {
$_SESSION["products"][$product['product_code']]["product_qty"] = $_SESSION["products"][$product['product_code']]["product_qty"] + $_POST["product_qty"];
} else {
$_SESSION["products"][$product['product_code']] = $product;
}
} else {
$_SESSION["products"][$product['product_code']] = $product;
}
}
$total_product = count($_SESSION["products"]);
die(json_encode(array('products'=>$total_product)));
}


Steps5: View cart details
In view_cart.php we will handle functionality to display cart details like product name, price, quantity, sub total, total etc. There are also functionality to add/remove product and change quantity of cart product.

<div class="text-left">
<div class="col-md-8">
<h3>My Cart (<span id="cart-items-count"><?PHP if(isset($_SESSION["products"])){echo count($_SESSION["products"]); } ?></span>)</h3>
<?php
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0) {
?>
<table class="table" id="shopping-cart-results">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){
$product_name = $product["product_name"];
$product_price = $product["product_price"];
$product_code = $product["product_code"];
$product_qty = $product["product_qty"];
$product_color = $product["product_color"];
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
?>
<tr>
<td><?php echo $product_name; echo "—"; echo $product_color; ?></td>
<td><?php echo $product_price; ?></td>
<td><input type="number" data-code="<?php echo $product_code; ?>" class="form-control text-center quantity" value="<?php echo $product_qty; ?>"></td>
<td><?php echo $currency; echo sprintf("%01.2f", ($product_price * $product_qty)); ?></td>
<td>
<a href="#" class="btn btn-danger remove-item" data-code="<?php echo $product_code; ?>"><i class="glyphicon glyphicon-trash"></i></a>
</td>
</tr>
<?php } ?>
<tfoot>
<br>
<br>
<tr>
<td><a href="index.php" class="btn btn-warning"><i class="glyphicon glyphicon-menu-left"></i> Continue Shopping</a></td>
<td colspan="2"></td>
<?php
if(isset($total)) {
?>
<td class="text-center cart-products-total"><strong>Total <?php echo $currency.sprintf("%01.2f",$total); ?></strong></td>
<td><a href="checkout.php" class="btn btn-success btn-block">Checkout <i class="glyphicon glyphicon-menu-right"></i></a></td>
<?php } ?>
</tr>
</tfoot>
<?php
} else {
echo "Your Cart is empty";
?>
<tfoot>
<br>
<br>
<tr>
<td><a href="index.php" class="btn btn-warning"><i class="glyphicon glyphicon-menu-left"></i> Continue Shopping</a></td>
<td colspan="2"></td>
</tr>
</tfoot>
<?php } ?>
</tbody>
</table>
</div>
</div>


Steps6: Checkout Order
In checkout.php, we will checkout order details with cart product, quantity, total, taxes etc before place order.

<?php
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
$total = 0;
$list_tax = '';
?>
<table class="table" id="shopping-cart-results">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php
$cart_box = '';
foreach($_SESSION["products"] as $product){
$product_name = $product["product_name"];
$product_qty = $product["product_qty"];
$product_price = $product["product_price"];
$product_code = $product["product_code"];
$product_color = $product["product_color"];
$item_price = sprintf("%01.2f",($product_price * $product_qty));
?>
<tr>
<td><?php echo $product_name; echo "—"; echo $product_color; ?></td>
<td><?php echo $product_price; ?></td>
<td><?php echo $product_qty; ?></td>
<td><?php echo $currency; echo sprintf("%01.2f", ($product_price * $product_qty)); ?></td>
<td> </td>
</tr>
<?php
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$grand_total = $total + $shipping_cost;
foreach($taxes as $key => $value){
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount;
}
foreach($tax_item as $key => $value){
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
$cart_box .= "<span>$shipping_cost $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</span>";
?>
<tfoot>
<tr>
<td><br><br><br><br><br><br><a href="index.php" class="btn btn-warning"><i class="glyphicon glyphicon-menu-left"></i> Continue Shopping</a></td>
<td> </td>
<td> </td>
<td class="text-center view-cart-total"><strong><?php echo $cart_box; ?></strong></td>
<td><br><br><br><br><br><br><a href="success.php" class="btn btn-success btn-block">Place Order <i class="glyphicon glyphicon-menu-right"></i></a></td>
</tr>
</tfoot>
<?php
} else {
echo "Your Cart is empty";
}
?>
</tbody>
</table>


You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

Komentar

  1. pls where is success. php code which contains the cart Info and insert to database

    BalasHapus
  2. Nice Tutorial

    BalasHapus
  3. if I choose 1 black and 1 while of the same product, it counts them as 2 of the same color product and this is not correct.

    BalasHapus
  4. Yes it is. You can make changes in script according to your requirement. I will also update demo to work like that. thanks!

    BalasHapus
  5. Thanks for comment! you need to implement cart payment success details into database. its not provided here in this tutorial.

    BalasHapus
  6. This is awesome. Please when the order is been place, the cart still remain there, which is not suppose to be so, and when are you updating the script?

    BalasHapus
  7. when order placed, its gone for payment but payment gateways not implement there. The Papal payment gateways integration done in next tutorial https://www.phpzag.com/shopping-cart-with-paypal-integration-in-php/.

    BalasHapus

Posting Komentar

Ads middle content1

Ads middle content2