In this tutorial we will learn add to cart using session in php. In my previous blog post I have created single product page. Now I am using same product page to apply add to cart feature. I will use php session for add to cart functionality. So let’s start.
HTML:
1 2 3 4 5 6 7 8 9 10 11 |
<form class="form-inline" method="POST"> <div class="form-group mb-2"> <input type="number" name="product_qty" id="productQty" class="form-control" placeholder="Quantity" min="1" max="1000" value="1"> <input type="hidden" name="product_id" value="<?php echo $getProductData['id']?>"> </div> <div class="form-group mb-2 ml-2"> <button type="submit" class="btn btn-primary" name="add_to_cart" value="add to cart">Add to Cart</button> </div> </form> |
As you can see in above code that I have wrapped product quantity and cart button under form. I also make one hidden input field in which I am setting product id. Also form has POST method.
PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
if(isset($_POST['add_to_cart']) && $_POST['add_to_cart'] == 'add to cart') { $productID = intval($_POST['product_id']); $productQty = intval($_POST['product_qty']); $sql = "SELECT p.*,pdi.img from products p INNER JOIN product_images pdi ON pdi.product_id = p.id WHERE pdi.is_featured =:featured AND p.id =:productID"; $prepare = $db->prepare($sql); $params = [ ':featured'=>1, ':productID' =>$productID, ]; $prepare->execute($params); $fetchProduct = $prepare->fetch(PDO::FETCH_ASSOC); $calculateTotalPrice = number_format($productQty * $fetchProduct['price'],2); $cartArray = [ 'product_id' =>$productID, 'qty' => $productQty, 'product_name' =>$fetchProduct['product_name'], 'product_price' => $fetchProduct['price'], 'total_price' => $calculateTotalPrice, 'product_img' =>$fetchProduct['img'] ]; if(isset($_SESSION['cart_items']) && !empty($_SESSION['cart_items'])) { $productIDs = []; foreach($_SESSION['cart_items'] as $cartKey => $cartItem) { $productIDs[] = $cartItem['product_id']; if($cartItem['product_id'] == $productID) { $_SESSION['cart_items'][$cartKey]['qty'] = $productQty; $_SESSION['cart_items'][$cartKey]['total_price'] = $calculateTotalPrice; break; } } if(!in_array($productID,$productIDs)) { $_SESSION['cart_items'][]= $cartArray; } $successMsg = true; } else { $_SESSION['cart_items'][]= $cartArray; $successMsg = true; } } |
Above code start with a condition of form submit and then I wrote a sql query to get data of that product from database. After getting product data and save in $fetchProduct
variable, I calculate the total price by multiplying quantity into product price. I also use number_format()
function to show 2 digits after decimal sign. Next I created an array using $cartArray
variable. Then I checked $_SESSION['cart_items']
condition to verify that current cart item is the first cart item or $_SESSION['cart_items']
already have cart items. If $_SESSION['cart_items']
is empty, then I add $cartArray
to $_SESSION['cart_items']
. Otherwise I iterate $_SESSION['cart_items']
using foreach
loop and match the current product is exist or not if current product is exist I will update its quantity and total price and break the loop. If current product is not present in $_SESSION['cart_items']
then I will add it in $_SESSION['cart_items']
Success Message:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php if(isset($successMsg) && $successMsg == true){?> <div class="row mt-3"> <div class="col-md-12"> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> <img src="<?php echo $imgUrl ?>" class="rounded img-thumbnail mr-2" style="width:40px;"><?php echo $getProductData['product_name']?> is added to cart. <a href="cart.php" class="alert-link">View Cart</a> </div> </div> </div> <?php }?> |
Once product will add and $successMsg
will set, I will show success message.
Show Cart Item Count:
1 2 3 4 5 6 7 8 9 10 |
<div class="form-inline my-2 my-lg-0"> <a href="cart.php" style="color:#ffffff"> <i class="bi bi-cart4" style="font-size:30px;"></i> <?php echo (isset($_SESSION['cart_items']) && count($_SESSION['cart_items'])) > 0 ? count($_SESSION['cart_items']):''; ?> </a> </div> |
In above code I am just printing cart items count.
Also read:
- PHP Shopping Cart – Step by Step
- PHP Shopping Cart – Setup Directory Structure and MYSQL Database
- PHP Shopping Cart – Display Products from Database
- PHP Shopping Cart – Create Single Product Page
- PHP Shopping Cart – Checkout code with validation