In this tutorial, I am demonstrating how to do step by step, a simple tutorial of a shopping cart with PHP 5.6 and MYSQL. This shopping cart application was developed very simple and simple for the learning purpose of all of us who like this language that has saved our lives at any time. One can take this as an easy shopping cart for any website, but this is purely an idea to create a shopping cart website.
<?php
//Config authentication with database
$conn = new PDO("mysql:host=localhost;dbname=demo_cart_php", 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Method for add products to shopping cart
Main File PHP: shopping-cart.php
Given below our full PHP code, copy to use it.
When the user presses the Add to shopping cart button, the product details will be saved in the shopping cart session with SKU and other details. The following code has the add action to the cart and adds the product to the shopping cart session.
If we click on the same product several times, the amount will increase.
<?php
//get action string
$action = isset($_GET['action'])?$_GET['action']:"";
//Conditional to add an added product to the basket
if($action=='addcart' && $_SERVER['REQUEST_METHOD']=='POST') {
//Finding the product by code
$query = "SELECT * FROM products WHERE sku=:sku";
$stmt = $conn->prepare($query);
$stmt->bindParam('sku', $_POST['sku']);
$stmt->execute();
$product = $stmt->fetch();
$currentQty = $_SESSION['products'][$_POST['sku']]['qty']+1; //Incrementing the product qty in cart
$_SESSION['products'][$_POST['sku']] =array('qty'=>$currentQty,'name'=>$product['name'],'image'=>$product['image'],'price'=>$product['price']);
$product='';
header("Location:shopping-cart.php");
}
//Empty all the shopping cart
if($action=='emptyall') {
$_SESSION['products'] =array();
header("Location:shopping-cart.php");
}
//Empty product one by one
if($action=='empty') {
$sku = $_GET['sku'];
$products = $_SESSION['products'];
unset($products[$sku]);
$_SESSION['products']= $products;
header("Location:shopping-cart.php");
}
//Get all Products
$query = "SELECT * FROM products";
$stmt = $conn->prepare($query);
$stmt->execute();
$products = $stmt->fetchAll();
?>
Call and list existing products in the database MySql
Main File PHP: shopping-cart.php
Given below our full HTML code, copy to use it.
- This html code lists the products that are added to the database and will be listed with their respective data such as description, price, name to add to the shopping cart by pressing the button.
"Add To Cart"
<div class="container">
<?php if(!empty($_SESSION['products'])):?>
<div class="alert alert-success" role="alert"><i class="fa fa-cart-plus"></i>
<a href="cart.php"> Go to shopping cart</a>
</div>
<?php endif;?>
<div class="adsense-snippet-all">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-8378091836388672"
data-ad-slot="5101783172"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div class="col-md-12">
<br>
<?php foreach($products as $product): ?>
<div class="col-sm-6 col-md-4">
<div class="thumbnail" >
<h4 class="text-center"><span class="label label-info">Category</span></h4>
<img src="<?php print $product['image']?>" class="img-responsive">
<div class="caption">
<div class="row">
<div class="col-md-6 col-xs-6">
<h3><?php print $product['name']?></h3>
</div>
<div class="col-md-6 col-xs-6 price">
<h3>
<label>$<?php print number_format($product['price']) ?></label>
</h3>
</div>
</div>
<p>32GB, 4GB Ram, 1080HD, 6.3 inches, WP 8</p>
<div class="row">
<div class="col-md-6">
<a class="btn btn-primary btn-product"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a>
</div>
<div class="col-md-6">
<form method="post" action="shopping-cart.php?action=addcart">
<div class="col-md-4 text-center">
<button class="btn btn-success"><span class="glyphicon glyphicon-shopping-cart"></span> Buy</button>
<input type="hidden" name="sku" value="<?php print $product['sku']?>">
</div>
</form>
</div>
</div>
<p> </p>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
<script type="text/javascript" src="assets/js/app.js"></script>
Step 3
File PHP: cart.php
- Next, our
php code to remove all the products added to the shopping cart that are already in session.
You also have the possibility to empty the cart.
<?php
error_reporting(0);
//Setting session start
session_start();
$total=0;
$amount=0;
//get action string
$action = isset($_GET['action'])?$_GET['action']:"";
//Empty All
if($action=='emptyall') {
$_SESSION['products'] =array();
header("Location:shopping-cart.php");
}
//Empty one by one
if($action=='empty') {
$sku = $_GET['sku'];
$products = $_SESSION['products'];
unset($products[$sku]);
$_SESSION['products']= $products;
if (!empty($_SESSION['products'])) {
header("Location:cart.php");
}else {
header("Location:shopping-cart.php");
}
}
?>
Call and list the existing products in the PHP session
File PHP: cart.php
Given below our full HTML and PHP code, copy to use it.
- This html code lists the products added to the php session that will contain the details of the added products, such as description, price, name, and id.
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-10 col-md-offset-1">
<table class="table table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php $count = 1 ?>
<?php foreach($_SESSION['products'] as $key=>$product):?>
<tr>
<td class="col-md-6">
<div class="media">
<a class="thumbnail pull-left" href="#"> <img class="media-object" src="<?php print $product['image']?>" style="width: 72px; height: 72px;"> </a>
<div class="media-body">
<h4 class="media-heading"><a href="#"><?php print $product['name']?> </a></h4>
<h5 class="media-heading"> by <a href="#">Brand name</a></h5>
<span>Status: </span><span class="text-warning"><strong>Leaves warehouse in 2 - 3 weeks</strong></span>
</div>
</div></td>
<td class="col-md-1" style="text-align: center">
<input disabled="" type="number" class="form-control" id="exampleInputEmail1" value="<?php print $product['qty'] ?>">
</td>
<td class="col-md-1 text-center"><strong>$<?php print number_format($product['price']) ?></strong></td>
<td class="col-md-1 text-center"><strong><?php print number_format($product['price']*$product['qty']) ?></strong></td>
<td class="col-md-1">
<!-- cart.php?action=empty&sku=<?php print $key?> -->
<a href="javascript:void(0)" data-id="<?php echo $key?>" data-title="Remove Item ?" type="button" class="btn btn-danger remove-item">
<span class="glyphicon glyphicon-remove"></span> Remove
</a>
<input type="hidden" id="remove-item" value="<?php echo $key?>">
</td>
</tr>
<?php $amount +=$product['price']*$product['qty']; ?>
<?php $count++; ?>
<?php endforeach; ?>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h5>Subtotal</h5></td>
<td class="text-right"><h5><strong><?php print number_format($amount) ?></strong></h5></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h5>Estimated shipping</h5></td>
<td class="text-right"><h5><strong><?php print number_format($amount) ?></strong></h5></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h3>Total</h3></td>
<td class="text-right"><h3><strong><?php print number_format($amount) ?></strong></h3></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<a href="cart.php?action=emptyall">
<button type="button" class="btn btn-warning">
<span class="glyphicon glyphicon-shopping-cart"></span> Empty Cart
</button>
</a>
</td>
<td>
<a href="shopping-cart.php">
<button type="button" class="btn btn-default">
<span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
</button>
</a>
</td>
<td>
<button type="button" class="btn btn-success">
Checkout <span class="glyphicon glyphicon-play"></span>
</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Confirm for remove item
File JAVASCRIPT: app.js
The remove () button removes the items added in the cart
$('a.remove-item').confirm({
title: 'Encountered an error!',
content: 'Remove product from the basket.',
type: 'red',
buttons: {
tryAgain: {
text: 'yes, remove',
btnClass: 'btn-red',
action: function(){
value = this.$target.attr('data-id');
location.href ="cart.php?action=empty&sku=" + value;
}
},
close: function () {
//event
}
}
});
I hope you liked this simple shopping cart with php 5.6 and mysql database