Simple Shopping Cart using PHP and MySQL

Demo Download

In this tutorial, we will create a Simple Shopping Cart using PHP and MySQL. Purpose of this tutorial 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 the PHP session to store items that are added by the user into cart.

What is Shopping Cart?

On the internet the shopping cart is simply an online application which is available over the internet on e-commerce websites, the visitors on the website can select and add different items into cart which they are intended to buy online.

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

Steps to Create a Simple Shopping Cart using PHP and MySQL

I have divided this tutorial into few steps to make it easier to understand its working.

  1. Create a Database, Table and Dump Sample Data
  2. Create a Database Connection
  3. Create an Index File
  4. Create a Cart File
  5. Create a CSS File

1. Create a Database, Table and Dump Sample Data

To create database run the following query in MySQL.

To create a table run the following query.

Note: I have already attached the SQL file of this table with dummy data, just download the complete zip file of this tutorial.

2. Create a Database Connection

Create a db.php file and paste the following database connection in it. Make sure that you update these credentials with your database credentials.

3. Create an Index File

Create an  index.php file and paste the following script in the beginning of your file.

The above script is just adding values of selected item into array so that we can display them into cart.php page.

Add the following script in the same file in body section to display a cart icon.

Add the following script in the same file after adding the above script to display products from database and display message after adding any product.

4. Create a Cart File

Create a  cart.php file and paste the following script in the beginning of file.

The above script is performing two different things based on chosen action. If user click on remove item button, it will remove item from the cart. And if user changes the selected item quantity, it will also update the item quantity in the session array. If you want to display cart icon here so you can do the same which we did above in  index.php file.

Add the following script in the body section of the  cart.php file.

The above script is simply displaying the products with full details, its price, units, image, and total amount. In here user can also select the quantity of its products. All messages of removing and adding quantity will also display here in the bottom. Sample screenshot is also attached below:

5. Create a CSS File

Create an  style.css file and paste the following style in it.

I try my best to explain this tutorial as simple as possible but if you still have any query you can leave it in comment section below, i will try to respond as soon as possible.

Demo Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Facebook Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.


  1. if (isset($_GET[‘pid’]) && $_GET[‘pid’] != “”) {
    $id = $_GET[‘pid’];
    // echo $id;
    $sql = “SELECT * FROM products WHERE product_id = ‘$id’ “;
    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($res);
    // print_r($row);

    $cart = array(

    $itemQty = “”;
    foreach ($cart as $key => $value) {
    $itemQty = $value[‘qty’];

    if (empty($_SESSION[‘cartData’])) {
    $_SESSION[‘cartData’] = $cart;
    } else {
    if (in_array($id, array_keys($_SESSION[‘cartData’]))) {
    $_SESSION[‘cartData’][$key][‘qty’] += $itemQty;
    } else {
    = array_merge($_SESSION[‘cartData’], $cart);

    Sir, Only first time it’s cheacking duplicate product, when add second product then it merge not quantity increase .. why..?

      1. yes sir, i have done this, the problem is that when we are fetching values from the static array, then it’s working fine but when i fetching the value from the database then associative array key is going on change….(while same code is working good with static array).

        1. Although my tutorial is fetching values from database table. May be there is something related to database on your side. Make sure it is working fine.

          Just try to display some results from the same table on the page, if it is getting results then put those results in your products.

  2. It was all working fine, but i put an item in the database with a code like ‘test’ and now i can’t remove it anymore from the cart page.

    1. Dear Marvin, Although you can store any value in code, it should be working accordingly. It may be possible that you changed the code value after adding item into cart. As it may be possible that session have different value of code while different value in database now.

      Products are displayed from database, it should work whatever code you are using but make sure each code should be unique.

    Good Day Sir Javed Ur Rehman ! May I ask what is the purpose of the SESSION for the shopping cart because when I modify it , it only show the data that you have inserted hence It could not load my data. Do you have any way to solve this perhaps?

  4. Hi sir, thank you for your codes but for me they are keep displaying warning of undefined index. and it showed me that the error is here:

    Buy Now

    May you help me to solve it!?

  5. Hi , It a good code it was working tone for me but I have a few questions.

    1. When I tried to modify the index.php by adding a header and a footer , when you click on the product, The entire page relodes and then nothing is added to the cart but before modifying it was doing fine .How can I go about it please.

    1. You will need to it carefully, as you can not write anything before session start. Similarly you do not want to write code between conditions. You will need to identify the location which will not impact the functionalities of program.

  6. Hi Javed, great piece of coding. Thanks for sharing!

    Just what I was looking for.

    A quick question:
    If I add some items, go to the cart and then go back with the back button of the browser. I get an error. It occurs in Firefox and Chrome

    Do you know how to avoid this because it’s not giving a great UX 😉

  7. I cant see anything, i have followed the correct steps even downloaded the zip file. My database is connected but nothing shows
    please help!

      1. Good Day

        I have a project that was created for me by someone who knows php. So I have the file from google drive(the practical project) but I dont know which software to install on my laptop since it was created by someone else.Please can you help me? I am really in need of your help Sir. Thank you so much

  8. sir how to to make shoping cart with the help og database like you made it using session so after end of session it will destroy but i want to make it real time like if any user login and add any item in cart and then logout now if the same user login then i want to show them their last item which they already added . so how can we do that?????

  9. Hi Javed,
    I have an issue in the code. I want to show the total items on the cart icon in the header. Eg, if I have 1 quantity of product A and 2 quantity of product B, so instead of showing 2 in the cart, I want to show 3.
    Please help.

  10. Hi, this is such a great coding! I’ve been looking everywhere for simple e-Commerce website & yours is the only one that works!
    But i’m having problem when i wanted to add to cart, this error occur

    “Notice: Trying to access array offset on value of type null in….”

    in line below (index.php)…

    $name = $row[‘name’];
    $code = $row[‘code’];
    $price = $row[‘price’];
    $image = $row[‘image’];

    But other function works. Can help me with that? Thank you.

  11. Man you are the Master thank you for this tutorial I really wish to see the fully operational cart though..

  12. Hi Javed, thanks for a nice tutorial. I was wandering, if you had quantity: 50 (50 options to select in the drop-down quantity menu), how would you create a loop, so you would not have to create 50 entries in your html/php?

  13. Hi thanks for the tutorial. It was very easy to understand and very easy to follow. I just don’t understand what is $_SESSION[“shopping_cart”]? What is it assigned to? in tutorial we start by checking if(empty($_SESSION[“shopping_cart”])), then in cart.php we do loop on $_SESSION[“shopping_cart”]. Can you explain the role of this session variable.

    Thank you

  14. How i want to put quantity field in this statement? in the index.php???

    $result = mysqli_query($conn,"SELECT * FROM products");
    while($row = mysqli_fetch_assoc($result)){
    echo "



    Buy Now



  15. Hi. I love the code and it is exactly what i was looking for. the problem start from the actual SQL code for me. i have downloaded the zip file but its still not executing. any suggestion?? From AUTO_INCREMENT onwards i have errors. thank you

  16. First of all thanks sir for this tutorial and i will not change anything in this cart.php file and i got error. Can you help me sir?

      1. Sir ADD to Cart is Working well.
        but next what we do.?
        payment method + Complete order
        Please make a tutorial

          1. Great to know that Javed.. This is awesome!!! Thanks for all the efforts for sharing your knowledge.

  17. Hi, hope you are well?

    I added all code in my project but problem when i execute i don’t get any error and there are no pictures showing,

    only the message below shows,

    “Demo Simple Shopping Cart using PHP and MySQL
    Tutorial Link
    For More Web Development Tutorials Visit:”

    Something i am missing perhaps??
    Thank you.

      1. Thank you for the response, i downloaded the whole tutorial, Shopping cart is working fine but pictures still don’t display.

    1. In simple shopping cart, after item is added only cart icon appear. But I need the cart icon initially with initial value 0.what code, I have to add

  18. Hi sir i have problem in my cart.php whenever i remove item not all of my items will be deleted even if many times i click it

  19. Sir, I’m really appreciate and proud of you always because, your works solve a lot of my problem, finally you are my mentor.

  20. Hello, So I want to display my images from database. I copied. path of my image from my computer, but it does not showing up. Then I used BOB type for image and it is showing me bunch of weird codes, CAN YOU PLEASE HELP ME OUT TO SHOW MY IMAGES????

  21. First off, thank you for this tutorial. I was able to incorporate this easily into my project. I just have one quick question, what’s the easiest way to clear out/empty the cart? Is it as simple as unset($_SESSION[“shopping_cart”]); ?

    Thanks for the help!

  22. Good day sir, but sir, how do we create payment method for the shopping cart to allow users to pay for selected product, please sir

    1. Hi Mark, this tutorial is only for the basic concept how shopping cart works, yes it does not contain online payment integration, because i wanted to keep it simple as possible and there are several online payment options that people uses so you can find them on Google.

  23. Hi, thanks for the tutorial! Can i ask how to center the products in the index page? I changed the pictures and now the whole products is aligned to the left side.

  24. Hi Thank you for sharing your knowledge where would we be without people like you. I have uploaded to server all files and the demo is working properly. I am not sure how to integrate just the cart part into my already made products page.

      1. Javed great article and very simple codebase. Helped me a lot.

        A small correction is required in the cart.php code in the article above to make Remove work
        Replace this code
        if($_POST[“code”] == $key)
        if($_POST[“code”] == $_SESSION[“shopping_cart”][$key][‘code’])

  25. Your shopping cart code is great! I have tried to modify my index.php as I only have one item displayed on a pop up. I need to be able to add multiples of one item to a cart, close the pop up and keep on adding items. How I can change the cart to add multiple items of a product to the shopping cart? I’m having problems with this section:

    $result = mysqli_query($con,"SELECT * FROM products");
    while($row = mysqli_fetch_assoc($result)){

    I've changed it to "SELECT * FROM products WHERE ProductID = '$_POST[ProductID]'"; but I keep on getting a ProductID undefined index error.

  26. First, thank you for this great tutorial, everything has turned out to be less when I select the quantity. I select the quantity and return to cart.php keeping the products and the values ​​but the input select is kept at 1

  27. This code really helped me, but in the end, in the cart.php I want to send the information + quantity to the database. just that, but I can’t work it out, can you help me, brother?

  28. Notice: Undefined index: price in C:\xampp\htdocs\ProjectFinal\index.php on line 64

    this error keeps showing and the index page doesnt show the price but shows all other information

  29. Hey i have a issue with the Code when i add a product i cant remove that. When i add a Second product in the cart i can remove that but the First one has still the issue. I didnt change any thing from the Code what can i do?

  30. Please sir I am using your code in my project. Can you help me with checkout process. How to checkout and move to Payment

  31. Thanks a lot what is the best way to save the selected cart items to the orders table. I understand that once we terminate the session the cart items will vanish from the cart. So how can we save what was selected to mysql database? Apparently the wide internet has not been helpful on this one or if you have a link I would appreciate.

  32. Sir if it is possible for you
    can you a make video tutorial for this same so I can understand this concept very well actually I am new in php and mysql

    1. Dear Prateek, i try my best to explain as simple as possible. I would suggest you to read more basic PHP concepts which can help you, i do not have any video channel so i hope you can find video tutorial of it on Google.

  33. I got the issue with merge array,
    after adding the first item immediately array index starts from 0,1,2,… how to resolve it

    1. If you are facing any issue, i would suggest you to download complete tutorial from download button and then try to run it.
      Currently the tutorial is working fine if you are adding or removing products. Where are you getting error on it?

  34. Undefined index: price in C:\xampp\htdocs\MAIN\Add-cart-4\demo\cart.php on line 98

    Undefined index: quantity in C:\xampp\htdocs\MAIN\Add-cart-4\demo\cart.php on line 98

    Notice: Undefined index: name in C:\xampp\htdocs\MAIN\Add-cart-4\demo\cart.php on line 74

  35. Hi I have created the php files as mentioned above and pasted codes in db.php,index.php,cart.php and style.css.I have also created allphptricks database and products table.

    But when m trying to execute localhost/cart/index.php , its showing blank.Please anyone help me!! urgent reply! stucking for long hours!!!!
    thanks in advance!

    1. Debug your error, first make sure your database is connected, then step by step check where are you getting error. Print different values on index page on different lines to check the error.

  36. Its a great tutorial, I have done all steps, but it cant connect with the cart.php file. It is showing ‘the fields are empty’

  37. // Enter your Host, username, password, database below. $con = mysqli_connect(“localhost”,”root”,””,”allphptricks”); if (mysqli_connect_error()){ echo “Failed to connect to MySQL: ” . mysqli_connect_error(); die(); }

    Sorry bro i get above error

  38. I liked your code, i have a code with me for cart, but i want to add that one feature of yours in the cart which restricts the user from adding 1 item more than once. can you edit my code:

    db = DB();

    * get products list
    * @return array
    public function getProducts()
    $query = “SELECT * FROM entertainment“;
    if (!$result = mysqli_query($this->db, $query)) {
    $data = [];
    if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;

    return $data;

    * get given product details
    * @param [integer] $id
    * @return array
    public function getProductDetails($id)
    $id = mysqli_real_escape_string($this->db, $id);
    $query = “SELECT * FROM entertainment WHERE id = ‘$id'”;
    if (!$result = mysqli_query($this->db, $query)) {
    $data = [];
    if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
    $data[‘id’] = $row[‘id’];
    $data[‘title’] = $row[‘title’];
    $data[‘price’] = $row[‘vendor_price’];
    $data[‘quantity’] = 1;

    return $data;

    * Add new product into the cart
    * @param [integer] $id
    * @return void
    public function addToCart($id)

    $product = $this->getProductDetails($id);

    $isFound = false;
    $i = 0;

    if (!isset($_SESSION[‘shopping_cart’]) || count($_SESSION[‘shopping_cart’]) $product);
    } else {

    foreach ($_SESSION[‘shopping_cart’] as $item) {
    foreach ($item as $key => $value) {
    if ($key == “id” && $value == $id) {
    array_splice($_SESSION[‘shopping_cart’], $i – 1, 1, array([
    ‘id’ => $item[‘id’],
    ‘title’ => $item[‘title’],
    ‘price’ => $item[‘vendor_price’],
    ‘quantity’ => $item[‘quantity’] + 1,
    $isFound = true;

    if ($isFound == false) {
    array_push($_SESSION[‘shopping_cart’], $product);


    * remove existing product from the cart
    * @param [integer] $id
    * @return void
    public function removeProductFromCart($id)
    unset($_SESSION[‘shopping_cart’][$id – 1]);



  39. Please I have problem. I did all steps but on cart.php the information for products that added don’t show
    show the fields are empty

  40. Hi bro actually i am stacked with one problem i just want to know is images also needed to save in database if its then how please help me

  41. Hi Javed, I have a few questions to ask,
    if (isset($_POST[‘action’]) && $_POST[‘action’]==”change”)
    what is $_POST[‘action] I don’t see any thing called action.

    if (isset($_POST[‘code’]) && $_POST[‘code’]!=””)
    what is and where is $_POST[‘code’] came from.

    Thank you for your help , hope to get your help soon.

      1. You provide very helpful code. Sir my query is How to work according to product varient. For example: price change according tshirt color.

    1. you want to send parameter value as “change” in postman
      if (isset($_POST[‘name’]) ==”change”)
      in postman you should send

      1. Do i sending any input field that have name as “name”? I am not sending any input field that name is used as name. When i am not sending anything so how can i get it? I am not able to understand what issue you are facing.

  42. Good day sir
    Please, I want to ask if I have 3 items displayed at the same time and I want my user to only select one and make payment based on the one selected and also get privileges based on the one selected. How do I do that e.g web hosting company selling hosting?

    1. Well, yes you can do it, all you need is to remove feature of add items, you will need to place restriction if one item is added hide add to cart button from the options, and for privilege you can make another table in database, add those privilege based on item id and display them once user selected that item in cart.

  43. Great tutorial!

    How would I go about adding a size selection form on the index.php and cart.php pages? In other words if I was selling T-shirt’s how could users select/change the size?


    1. You will require payment integration, it depends what kind of payment solution you are providing, there are several payment options available with integration guide, so choose any one and integrate with your website.

    1. Dear Andrea,

      Images are not stored in Database, only image name and locations may be stores in database, while the image files will be uploaded on your host, then you can display images by calling their name and location from database.

  44. Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /Applications/XAMPP/xamppfiles/htdocs/cake/customer/cartproduct.php on line 64
    I get one of the following error messages in below code, why?

    $image_query = mysqli_query($connection,”SELECT * FROM products“);
    while($row = mysqli_fetch_assoc($image_query)){
    echo ”

    Buy Now


  45. Wow Javed, you have done a great job, in which i could code this from the start like you, am really really willing to learn PHP in a full level. But Javed, the project is not complete, how can i submit it to the database?

Leave a Reply

Your email address will not be published. Required fields are marked *