PHP and MySQLi Shopping Cart using PHP SESSION to store Cart Data

PHP and MySQL Shopping Cart using PHP SESSION to store Cart Data
PHP and MySQL Shopping Cart using PHP SESSION to store Cart Data.
In this Article, I am going to create a PHP and MySQLi Shopping Cart using PHP SESSION to store Cart Data. The main Purpose of this Article is to explain the basic concept of shopping cart and how to use PHP session to store values into array of cart. 

eCommerce websites usually uses Shopping Cart using PHP SESSION to store data to cart. That are added by the user into cart. Multiple Products can be added using shopping cart by user. The products added into cart using PHP SESSION. If once order done by user at this time this user session will be unset and another session id will generate by the system.

If you are looking for a simple PHP session MySQL shopping cart tutorial. Then this article for you. In this article, I am going to create shopping cart step by step and understandable to you easily. So you can follow this article to create PHP shopping cart. In this article am going to show you how to make a simple PHP shopping cart application using PHP session. This script is purposely kept as simple as possible for beginner PHP programmer. Here I have to explain how to displaying product list from MySQL using PHP. For each displaying product we have given options for entering item quantity and add that item to shopping cart and that shopping cart items will be stored into a session variable and if you want to remove item from shopping cart then you can clear session variable and can removing items from the shopping cart. I used very simple PHP code for creating this shopping cart by using get and post methods of PHP.

What is Shopping Cart?

In the era of internet the shopping cart is available on e-commerce websites, the visitors of this website who want to buy products can easily select and add different items into cart. Using PHP SESSION, a session code will generate for the user and all the selected products are added into cart with session code. If once order done the session code for this user will be unset and new session code will be generated for new user. 

So lets, start creating a shopping cart using PHP and MySQLi and PHP SESSION.

Steps to Create a Shopping Cart using PHP and MySQLi:

I will explain this article into few steps to make it easier to understand.

Prepare the database :
  • Database design.
  • Create a database "shopping_cart".
  • Create "products" table.
  • Create "cart" table.
Website Design :
  • Create Config Page.
  • Create Header Page.
  • Create Index Page.
  • Create Footer Page.
  • Create Products Page.
  • Create ajax Page. 
  • Create functions Page. 
Cart Table Design:
PHP and MySQL Shopping Cart using PHP SESSION to store Cart Data
Products Table Design:
PHP and MySQL Shopping Cart using PHP SESSION to store Cart Data
config.php

<?php
$username="root";  
$password="";  
$hostname = "localhost";  
//connection string with database  
$dbhandle = mysqli_connect($hostname, $username, $password)  
or die("Unable to connect to MySQL");  
echo "";  
// connect with database  
$selected = mysqli_select_db($dbhandle, "shopping_cart")  
or die("Could not select examples"); 
?>

Create PHP SESSION: 
This PHP SESSION code should be placed in the top of index page. So that, The session code can be created for the user. That's SESSION code will be used to store cart data into cart table. This SESSION code will be unique per user.

<?php
if(empty($_SESSION["temp_sess"])){
    $_SESSION["temp_sess"]=md5(date("Ymdhis"));
}
?> 

Now, I am going to show all the products in "products.php" page, At first, in this page i will display all the products from database table named "products". For this purpose i need to add css file to decorate the product page. In each row i have shown only four product. I have used bootstrap and custom css to create product page. I have used bootstrap card to display products. In this card I have shown product image, product price, Product category, Add to Cart Icon and Product Details Button. If you click on product details button then the details of this product will be visible with a Bootstrap Modal. The customer can easily get all details of the specific product.
PHP and MySQL Shopping Cart using PHP SESSION to store Cart Data

The cart icon is used to add the products into cart. Multiple products will be added by clicking cart icon. If customer click this icon for first time then this product will be added into cart by one. Again this customer click on this icon then the product quantity will be increased by one. Actually every time the product quantity will be added by one by using customer click on the same cart icon. The added products will be shown in the header section. There is a Shopping Basket Icon in the header section. By Clicking this Shopping basket you will get a bootstrap modal and you will get all the products list those added by you. 

Actually I have used a function in cart icon. When you click the cart icon it call this function and Using this function i have created a ajax page so that without reload you can get all of your added products those you added in your cart table. Your all products insert into cart table using this ajax page. After inserting all products into cart table it automatically show all of them in the Shopping basket area. That's why the user will get all of the added products from cart those added by him/her without reload.

Code of product page:

<div class="row">           
<?php
$result = mysqli_query($dbhandle,"select * from products");     while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<div class="col-md-3">
<div class="single-offers">
<div class="offer-image">
<a href="#">
<?php
echo "<img src='userlogin/upload/products/$row[product_image]'>";
?>
</a>
</div>
<div class="offer-text">
<h4><?php echo $row["product_name"];?></h4>
<h6><?php echo "( ". $row["product_type"] . " )"?></h6>
<p><?php echo $row["product_price"];?></p>
<div class="offer-action">
<a href="javascript:0" onclick="sub_total();" class="offer-btn-1 np"><i style="font-size: 20px" title="Add To Cart" class="fa fa-shopping-cart" onclick="add_cart(<?php echo $row['id'];?>);"></i></a>
<a href="javascript:0" class="offer-btn-2" data-toggle="modal" data-target="#viewProduct<?php echo $row['id'];?>">Details</a>
</div>
<!-- start Modal for View product details -->
<div id="viewProduct<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">PRODUCT DETAILS</h4>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
<table class="table borderless"> 
<tbody> 
<tr> 
<td colspan="2"> 
<?php
echo "<img src='userlogin/upload/products/$row[product_image]' width='150px' height='150px'>";
?>
</td>
</tr>
<tr> 
<td>Product Name</td>
<td><?php echo $row["product_name"];?></td>
</tr>
<tr> 
<td>Product Code</td>
<td><?php echo $row["product_code"];?></td>
</tr>
<tr> 
<td>Product Price</td>
<td><?php echo $row["product_price"];?></td>
</tr>
<tr> 
<td colspan="2"> 
<p style="text-align: justify"><?php echo $row["product_description"];?></p>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>

</div>
</div>
<!-- End Modal for View product details -->
</div>
</div>
</div>
<?php
}
?>
</div>

I have use a function named "add_cart" in the above code. Using this function i have passed the product id into the ajax page. So that user can insert the product by per click. Actually this function will call according per click on cart icon. When product id will reach into ajax page all the information of the product according to product id can get easily. That's why is' so simple to insert all of the information of the specific product id. In ajax Page After insert query there is another query that is responsible for displaying the added products in Shopping basket. 

The sample code of Ajax call:

<script> 
function add_cart(str) { 

var xhttp; if (str.length == 0) { 
document.getElementById("cinfo").innerHTML = ""; 
return; 
}
xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { 
if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("cinfo").innerHTML = xhttp.responseText; 
}; 
xhttp.open("GET", "add_cart.php?id="+str, true); xhttp.send(); 
sub_total(); 
</script>


<!--Script for getting Total Price from cart-->

<script>

function sub_total() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("total_price").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "sub_total.php", true);
xhttp.send();   
}
</script>

By the above function we can pass the product id into ajax page. Here i am using PHP GET method to pass the product id into ajax page. add_cart.php is the ajax page.

The sample code of Ajax Page:

<?php

session_start();
include("config.php");
include("functions.php");

$tempSession = $_SESSION["temp_sess"];

if(isset($_GET["id"]) && $_GET["id"]!=""){
$id = $_GET["id"];

$result = mysqli_query($dbhandle," SELECT * FROM `products` WHERE `id`='$id' ");

$data = mysqli_fetch_array($result);

$check = mysqli_query($dbhandle,"SELECT * FROM `cart` WHERE `food_id`='$id' AND `session`='$tempSession'");
if(mysqli_num_rows($check)>0){
$checkResult = mysqli_fetch_array($check);
$qnty = $checkResult["quantity"];
$qnty = $qnty + 1;
$update = mysqli_query($dbhandle,"UPDATE `cart` SET `quantity`='$qnty' WHERE `food_id`='$id' AND `session`='$tempSession'");
}else{
$addToCart = mysqli_query($dbhandle,"INSERT INTO `cart` (`food_id`, `quantity`, `price`, `session`) VALUES ('$id', '1', '".$data["product_price"]."', '$tempSession')");
}
}
$getProduct = mysqli_query($dbhandle," SELECT * FROM `cart` WHERE `session`='$tempSession' ");
while($cartData = mysqli_fetch_array($getProduct)){

//using getProductInfo function for getting product info
$productInfo = getProductInfo($dbhandle, $cartData["food_id"]);

echo "<tr>";
echo "<td width='5%'>"; 
echo "<a href='javascript:0' style='color: red' onclick='remove(".$cartData['id'].");'><i class='fa fa-trash'></i></a>";
echo "</td>";

echo "<td width='65%'>"; 
echo "<span style='color: #000'>".$productInfo["product_name"]."</span>";
echo "</td>";

echo "<td width='5%'>";
echo "<input type='text' id='quantity' value='".$cartData["quantity"]."' style='width: 30px; text-align: right; border: none' >";
echo "</td>";

echo "<td width='25%'>";
echo "<input type='text' id='price' value='".$cartData["quantity"]*$productInfo["product_price"]."' style='text-align: right; width: 80px;border: none'>";
echo "</td>";
echo "</tr>";
}
?>

In the above code i have include functions.php page. Actually, This page is some mini function. So that i can get easily all the information of the product.

The sample code of Functions Page:

<?php
include("config.php");
function getProductInfo($dbhandle, $id){
$query = mysqli_query($dbhandle," SELECT * FROM `products` WHERE `id`='$id' ");
$result = mysqli_fetch_array($query);
return $result;
}
?>

In the above code, i have used sub_total.php page. Actually this page will calculate total price of the added products by users. 

The sample code of sob_total.php Page:

<?php
session_start();
include("userlogin/config/config.php");
include("userlogin/config/functions.php");

$tempSession = $_SESSION["temp_sess"];

$query = mysqli_query($dbhandle,"SELECT SUM(quantity*price) as total FROM `cart` WHERE `session`='".$_SESSION["temp_sess"]."' ");
$data = mysqli_fetch_array($query);
echo "TK. ". $data["total"];

?>

And finally in the following, there is code of display added products from cart table.

The sample code of header.php Page:

<div class="form-group" style="padding:10px">
<a data-toggle="modal" data-target="#myModal" style="color: #6C3483; cursor: pointer" title="Shopping Busket"><i class="fa fa-shopping-bag fa-2x"></i><span style="position: relative; font-weight: bold; color: red; font-size: 15px; right: 19px;"> 
<?php 
$tempSession = $_SESSION["temp_sess"];
$getProduct = mysqli_query($dbhandle," SELECT * FROM `cart` WHERE `session`='$tempSession' ");
echo $count = mysqli_num_rows($getProduct);
?></span></a>

<!-- Start Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" style="color: #000">YOUR ORDERS</h5><button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div class="modal-body">
     
<table class="table borderless"> 
<thead> 
<tr> 
<th width="5%" style="color: #000; font-weight: bold">ACTION</th>
<th width="65%" style="color: #000; font-weight: bold">PRODUCT NAME</th>
<th width="5%" style="color: #000; font-weight: bold">QUANTITY</th>
<th width="25%" style="color: #000; font-weight: bold; text-align: right;">AMOUNT</th>
</tr>
</thead>
<tbody id="cinfo">
<?php
$tempSession = $_SESSION["temp_sess"];
$getProduct = mysqli_query($dbhandle," SELECT * FROM `cart` WHERE `session`='$tempSession' ");
while($cartData = mysqli_fetch_array($getProduct)){

$productInfo = getProductInfo($dbhandle, $cartData["food_id"]);
?>
<tr>

<td> 
<a href="javascript:0" style="color: red" onclick="remove(<?php echo $cartData['id'];?>);"><i class="fa fa-trash"></i></a>
</td>
<td> 
<span style="color: #000"><?php echo $productInfo["product_name"];?></span>
</td>
<td>
<input type="text" id="quantity" value="<?php echo $cartData["quantity"];?>" style="width: 30px; text-align: right; border: none" >
</td>
       
<td>
<input type="text" id="price" value="<?php echo $cartData["quantity"]*$productInfo["product_price"];?>" style="text-align: right; width: 80px; border: none" >
</td>
</tr>
<?php
}
?>
</tbody>
<tfooter>
<tr> 
<td colspan="3" style="color: #000; text-align: right; font-weight: bold"> 
<span>TOTAL</span>
</td>
<td colspan="2" style="color: #000; text-align: right; font-weight: bold">
<span id="total_price">
<?php
$query = mysqli_query($dbhandle,"SELECT SUM(quantity*price) as total FROM `cart` WHERE `session`='".$_SESSION["temp_sess"]."' ");
$data = mysqli_fetch_array($query);
echo "TK. ". $data["total"];
?>
</span>
</td>
</tr> 
</tfooter>
</table> 
</div>
<div class="modal-footer">
<a class="btn btn-success btn-sm" href="?order=confirm">CHECK</a>
</div>     
</div>
</div>
</div>
<!-- End Modal -->
</div>

The preview of Shopping basket Icon:


All setup is OK. Now customer after added the products into cart he/she will get the all list of added products by clicking this shopping basket.

That's all to create a PHP and MySQLi Shopping Cart using PHP SESSION to store Cart Data.


EmoticonEmoticon