Shopping Cart Script using Session Array

 Shopping cart plus2-cart-v1 This shopping cart script uses two dimensional session array to store product id and quantity as selected by customer. We used PHP script to manage backend and MySQL database to store the products. JQuery is used at front end and Bootstrap 4 is used for style effects of this script. Selected products with quantity are stored in a two dimensional session array.

Learn the Basics of Two dimensional array shopping cart scripts

This script uses three main parts .
  1. Products Display with options to add , remove and change quantity
  2. Display the cart with products and calculate the price by using unit price , quantity, sub total and grand total.
  3. Remove all the products from Cart.

Displaying products with options to add , remove and update the Cart

Product display for shopping cart
We will display the products by taking data from a MySQL table. In our table, against each product we have stored the path of the image of the product, product Id ( p_id) ,product name, unit price.

How to display images by taking data from MySQL table.

Displaying Product with Quantity matching to Cart

While displaying the products , we will display JQuery UI spinner to show the quantity of the product available in the cart. If the product is not there in shopping cart then the spinner ( quantity ) will show 1 and user can change to any value within a maximum limit of 10. We have done this by using PHP code at the loading of the products page. We read the quantity available against each product and then set the value of the spinner.
$qty=1; // default value of quantity set to 1 
	if(isset($_SESSION[cart])){
	foreach ($_SESSION['cart'] as $key => $val) {
       if($row[p_id]=== $_SESSION['cart'][$key]['p_id']){
		$qty=$_SESSION['cart'][$key]['qty'];
		break;
	   }
	}
	}
The variable $qty we will use to set the default value of each record ( Product ) while displaying inside while loop.
  echo "<table class='table my_table'>
<tr class='info'><th>Picture</th> <th> ID</th><th>Name</th><th>Quantity</th><th>Unit Price</th><th>Add</th><th>Remove</th></tr>";
while ($row = $stmt->fetch_assoc()) {
	$qty=1; // default value of quantity set to 1 
	if(isset($_SESSION[cart])){
	foreach ($_SESSION['cart'] as $key => $val) {
       if($row[p_id]=== $_SESSION['cart'][$key]['p_id']){
		   $qty=$_SESSION['cart'][$key]['qty'];
		   break;
	   }
	}
	}
	echo "<tr><td ><img src=images/$row[img] class=rounded></td><td>$row[p_id]</td><td >$row[p_name]</td><td><input class='selector' id=$row[p_id]_qty size=2 value='$qty' data-sp_id=$row[p_id]></code> </td><td >$row[price] </td><td ><img src=cart-add.jpg class='img-thumbnail cart-add' id=$row[p_id]> </td><td><img src=cart-remove.jpg class='img-thumbnail cart-remove' data-remove_id=$row[p_id]> </td></tr>";
    }
echo "</table>";
After changing the quantity, the product will automatically added to the cart along with the quantity ordered ( set by user through spinner ) . By making the quantity equal to 0 , user can remove the product from shopping cart.

Adding products to Cart by button

Default quantity of each product is kept at 1, to add this quantity user can click the add button against the record to store the product id and quantity in our cart. We used common class for all add buttons ( class='img-thumbnail cart-add' ). We used my_function() to send product id and quanity to backend script.
$('.cart-add').click(function(){
var id=$(this).attr('id');
var qty=$('#'+id+'_qty').val();
my_function(id,qty); // Post data using Function
})
By changing the quantity cart will be update with new data. Product will be removed from the cart by making quantity equal to zero.

Adding products by changing Quantity ( Spinner )

Inside Shopping cart, quantity for the product will be incremented or decremented with the change of value of the spinner ( quantity ). There is a button for users to add products with default quantity to the shopping cart, however with change in quantity by Spinner , the cart gets automatically updated.
$( ".selector" ).spinner({
	max: 10,
  min: 0,
  stop:  _.debounce(function(e, ui) {
	var id=$(this).data('sp_id');
	var qty=$('#'+id+'_qty').val();
	
	my_function(id,qty); 
	
	}, 500)
 });
We used debounce function to introduce some delay while changing the value of the spinner.
var debouncedStop = _.debounce(function(e, ui) {
      show_error();
}, 10000);
By setting the spinner (quantity ) to 0 , the product can be removed from the shopping cart.

Removing products from Cart

While displaying the products with details , there is an option to change the quantity, customer can remove the product by changing the quantity to zero.

User can click the remove button against each product to remove the item from the cart. We used class='cart-remove' for all remove buttons of the products.
$('.cart-remove').click(function(){// remove button is clicked. 
my_function($(this).data('remove_id'),0);//Post data
$('#'+$(this).data('remove_id')+'_qty').spinner("value",0);
})
In the above code we are sending product id and quantity = 0 to backend script. After posting we are setting the corresponding spinner value to 0

As discussed above there are three events which affects the Cart and against each of these events we Post product id and quantity to our backend script add.php .

These three events pass product id and quantity through POST method.
1.Addition of product ( product id and quantity equal to 1 ) through button
2.Change in Quantity ( product id and quantity ) through spinner
3.Remove Product (product id and quantity equal to zero ) through button

In all the above three cases we will post Product Id ( p_id ) and Quantity ( qty ) to backend script add.php . For this we will prepare a common JQuery function which we can call on triggering of different events. This function post data and receive the status of the backend posting and show the message to user.
my_function=function my_function(id,qty){
$.post('add.php',{'p_id':id,'qty':qty},function(return_data){

$("#msg_display").html(return_data.msg);     
$("#size_of_cart").html(return_data.size_of_cart);
$("#msg_display").show();
setTimeout(function() { $("#msg_display").fadeOut('slow'); }, 4000);
},"json");
}

Displaying Number of products in Cart

At the top right of the page we will display number of items present in the cart. This is same as counting number of elements present inside an array.
<button type='button' class='btn btn-primary'>
  Number of Items in the cart = <span id=size_of_cart class='badge badge-light'>".sizeof($_SESSION['cart']). "</span>
  
</button>
After every update of the cart we will count the total number of elements ( products ) present and accordingly change the value using JQuery.
$("#size_of_cart").html(return_data.size_of_cart);
In above code size_of_cart is returned by our backend script add.php file with a value equal to number of elements present inside our $_SESSION[cart] array.



Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    12-06-2020

    Very helpful. Thanks.

    08-09-2020

    Great article and examples! It saved a lot of time. It is just what I needed.

    13-02-2021

    Very good.Thank you very much.

    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer