PHP Shopping Cart – Add to Cart using Session

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.

php add to cart form

HTML:

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:

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:

php add to cart success message

Once product will add and $successMsg will set, I will show success message.

Show Cart Item Count:

In above code I am just printing cart items count.

Also read:

 

Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.