Simple Shopping Cart using PHP and MySQL
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.
I have shared a separate tutorial for PayPal Payment Integration in PHP, if you want to integrate PayPal payment with this shopping cart on your website follow the PayPal Payment Gateway tutorial.
Alternatively, you can also integrate other payment services and I have also shared the complete process of Authorize.Net payment gateway integration using PHP.
Readers Also Read: Integrate Stripe Payment Gateway using PHP
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.
Readers Also Read: Laravel 10 User Roles and Permissions
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.
- Create a Database, Table and Dump Sample Data
- Create a Database Connection
- Create an Index File
- Create a Cart File
- Create a CSS File
1. Create a Database, Table and Dump Sample Data
To create database run the following query in MySQL.
CREATE DATABASE allphptricks;
To create a table run the following query.
CREATE TABLE IF NOT EXISTS `products` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`code` varchar(100) NOT NULL,
`price` double(9,2) NOT NULL,
`image` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
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.
// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","allphptricks");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
3. Create an Index File
Create an index.php file and paste the following script in the beginning of your file.
<?php
session_start();
include('db.php');
$status="";
if (isset($_POST['code']) && $_POST['code']!=""){
$code = $_POST['code'];
$result = mysqli_query(
$con,
"SELECT * FROM `products` WHERE `code`='$code'"
);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
$code = $row['code'];
$price = $row['price'];
$image = $row['image'];
$cartArray = array(
$code=>array(
'name'=>$name,
'code'=>$code,
'price'=>$price,
'quantity'=>1,
'image'=>$image)
);
if(empty($_SESSION["shopping_cart"])) {
$_SESSION["shopping_cart"] = $cartArray;
$status = "<div class='box'>Product is added to your cart!</div>";
}else{
$array_keys = array_keys($_SESSION["shopping_cart"]);
if(in_array($code,$array_keys)) {
$status = "<div class='box' style='color:red;'>
Product is already added to your cart!</div>";
} else {
$_SESSION["shopping_cart"] = array_merge(
$_SESSION["shopping_cart"],
$cartArray
);
$status = "<div class='box'>Product is added to your cart!</div>";
}
}
}
?>
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.
<?php
if(!empty($_SESSION["shopping_cart"])) {
$cart_count = count(array_keys($_SESSION["shopping_cart"]));
?>
<div class="cart_div">
<a href="cart.php"><img src="cart-icon.png" /> Cart<span>
<?php echo $cart_count; ?></span></a>
</div>
<?php
}
?>
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.
<?php
$result = mysqli_query($con,"SELECT * FROM `products`");
while($row = mysqli_fetch_assoc($result)){
echo "<div class='product_wrapper'>
<form method='post' action=''>
<input type='hidden' name='code' value=".$row['code']." />
<div class='image'><img src='".$row['image']."' /></div>
<div class='name'>".$row['name']."</div>
<div class='price'>$".$row['price']."</div>
<button type='submit' class='buy'>Buy Now</button>
</form>
</div>";
}
mysqli_close($con);
?>
<div style="clear:both;"></div>
<div class="message_box" style="margin:10px 0px;">
<?php echo $status; ?>
</div>
4. Create a Cart File
Create a cart.php file and paste the following script in the beginning of file.
<?php
session_start();
$status="";
if (isset($_POST['action']) && $_POST['action']=="remove"){
if(!empty($_SESSION["shopping_cart"])) {
foreach($_SESSION["shopping_cart"] as $key => $value) {
if($_POST["code"] == $key){
unset($_SESSION["shopping_cart"][$key]);
$status = "<div class='box' style='color:red;'>
Product is removed from your cart!</div>";
}
if(empty($_SESSION["shopping_cart"]))
unset($_SESSION["shopping_cart"]);
}
}
}
if (isset($_POST['action']) && $_POST['action']=="change"){
foreach($_SESSION["shopping_cart"] as &$value){
if($value['code'] === $_POST["code"]){
$value['quantity'] = $_POST["quantity"];
break; // Stop the loop after we've found the product
}
}
}
?>
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.
<div class="cart">
<?php
if(isset($_SESSION["shopping_cart"])){
$total_price = 0;
?>
<table class="table">
<tbody>
<tr>
<td></td>
<td>ITEM NAME</td>
<td>QUANTITY</td>
<td>UNIT PRICE</td>
<td>ITEMS TOTAL</td>
</tr>
<?php
foreach ($_SESSION["shopping_cart"] as $product){
?>
<tr>
<td>
<img src='<?php echo $product["image"]; ?>' width="50" height="40" />
</td>
<td><?php echo $product["name"]; ?><br />
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>" />
<input type='hidden' name='action' value="remove" />
<button type='submit' class='remove'>Remove Item</button>
</form>
</td>
<td>
<form method='post' action=''>
<input type='hidden' name='code' value="<?php echo $product["code"]; ?>" />
<input type='hidden' name='action' value="change" />
<select name='quantity' class='quantity' onChange="this.form.submit()">
<option <?php if($product["quantity"]==1) echo "selected";?>
value="1">1</option>
<option <?php if($product["quantity"]==2) echo "selected";?>
value="2">2</option>
<option <?php if($product["quantity"]==3) echo "selected";?>
value="3">3</option>
<option <?php if($product["quantity"]==4) echo "selected";?>
value="4">4</option>
<option <?php if($product["quantity"]==5) echo "selected";?>
value="5">5</option>
</select>
</form>
</td>
<td><?php echo "$".$product["price"]; ?></td>
<td><?php echo "$".$product["price"]*$product["quantity"]; ?></td>
</tr>
<?php
$total_price += ($product["price"]*$product["quantity"]);
}
?>
<tr>
<td colspan="5" align="right">
<strong>TOTAL: <?php echo "$".$total_price; ?></strong>
</td>
</tr>
</tbody>
</table>
<?php
}else{
echo "<h3>Your cart is empty!</h3>";
}
?>
</div>
<div style="clear:both;"></div>
<div class="message_box" style="margin:10px 0px;">
<?php echo $status; ?>
</div>
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.
.product_wrapper {
float:left;
padding: 10px;
text-align: center;
}
.product_wrapper:hover {
box-shadow: 0 0 0 2px #e5e5e5;
cursor:pointer;
}
.product_wrapper .name {
font-weight:bold;
}
.product_wrapper .buy {
text-transform: uppercase;
background: #F68B1E;
border: 1px solid #F68B1E;
cursor: pointer;
color: #fff;
padding: 8px 40px;
margin-top: 10px;
}
.product_wrapper .buy:hover {
background: #f17e0a;
border-color: #f17e0a;
}
.message_box .box{
margin: 10px 0px;
border: 1px solid #2b772e;
text-align: center;
font-weight: bold;
color: #2b772e;
}
.table td {
border-bottom: #F0F0F0 1px solid;
padding: 10px;
}
.cart_div {
float:right;
font-weight:bold;
position:relative;
}
.cart_div a {
color:#000;
}
.cart_div span {
font-size: 12px;
line-height: 14px;
background: #F68B1E;
padding: 2px;
border: 2px solid #fff;
border-radius: 50%;
position: absolute;
top: -1px;
left: 13px;
color: #fff;
width: 20px;
height: 20px;
text-align: center;
}
.cart .remove {
background: none;
border: none;
color: #0067ab;
cursor: pointer;
padding: 0px;
}
.cart .remove:hover {
text-decoration:underline;
}
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.
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
Twitter Official Page: All PHP Tricks
I like this shopping cart and the tutorial, easy to follow, the code is easy to implement and in general is very well explained.
Thank you.
Dear Jorge, thanks for the appreciation.
Sir, where is product checout code?
Dear Angel Roi,
This is simple shopping cart tutorial which does not include the payment integration. However, I have separately shared tutorials about payment integration, you can integrate this system to your desired payment integration such as PayPal, Authorize.Net or PayPal.
All payment integration tutorials links are available in this tutorial beginning and in demo link which is available in the website header menu.
Thanks I appreciate your time and your results.
How ever after implementing the code is not working? ;(
Dear William,
Debug your code and let me know at which point you are exactly facing problem.
This tutorial provides a clear explanation of how to create a Simple Shopping Cart using PHP and MySQL. It helps me a lot!
Dear Sabina,
I am glad that you found this tutorial helpful.
Is this format for app or website?
It is a tutorial for website.
button add to cart not working for me nor can i see the cart icon.Please help.
Dear Chandrika,
Cart icon is just an image, inspect it using chrome to see if it is linked with the correct image which should be present in the image source location.
If button add to cart is not working, then you can echo it, add to cart is simply a form submit, if your form is submitting then you can echo it, it your form is not submitting, then you will need to make sure that you exactly copy paste my code, I would suggest to first download and run my code without making any changes in it. Then you can make changes as per your need.
Good, but it is usable only as the example shown. If we use it as a real shopping cart, when user loads a second product page and ads a new product to cart then the array ids change from product code into 0,1,2,3 etc.. This causes issues to the cart functions like remove. The array is able to keep product code only in the same page, when a new product page loads, it removes the product code and replaces with numbers starting 0. is it possible to fix ?
Well I will suggest you to keep your product code in alpha number, if you will use only digits for product code, you may face issues. Hope this will help you out.
When i press add to cart or buy now its showing
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\project\onion.php on line 10
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\project\onion.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\project\onion.php on line 12
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\project\onion.php on line 13
and the PHP line contains this
$name = $row[‘name’];
$code = $row[‘code’];
$price = $row[‘price’];
$image = $row[‘image’];
Please can you a help Please
Well dear Sanil, first I would like to advice you to download and try to execute my code first. I didn’t create any file with name onion.php, If you are able to run my code without any error then you can make changes in it. Second I think you must check if you have added records in `products`, simple print_r($row) before $name = $row[‘name’]; to check that your database table have some data or not. Hope this will help you out.
I was looking to buy the advanced pack of the ecommerce but i want to know if i can be able to add content on the layout through the source code
Yes it is possible to modify the shopping cart as per your requirement. Contact me on my email [email protected] with details.
Thank you for this! Very helpful but I have a question. If you save the cart details in session, how do you pass the data to the database so the admin can see it on the admin panel that an order has being placed with the details of the cart.
Dear Kanu, your question is valid, this tutorial does not contain payment processing, usually purchased information is stored in the database after successful purchase.
You can easily insert the data into your database from session array. You will simply need tp loop through the session variable and insert your session table to the relevant table.
You can check me other tutorial https://www.allphptricks.com/paypal-payment-integration-in-php/ which store information into database after successfully payment.
Hi Javed
Great tutorial it has helped me massively to write code for my own PHP cart as I am a complete beginner!
I am having one issue though on the index page I have used images for different products to yours however they all appear as different sizes is there anyway to fix this so all the images are the same size on the page just like in the cart I’ve been trying to figure it out for hours now.
Dear George, you can apply width to your images either through CSS class or directly into HTML attribute. style=”width: 100px;”
This will display all images to 100px, height will be adjusted accordingly.
Thanks for the quick reply Javed! I’ve tried writing it in css and in the html part but it just affects the border around the images when you hover over it and then it squishes all the images on top of each other I’m still not sure where to write it?
Thank you again for the great tutorial I have made so much progress!
Dear George, thanks for the appreciation. It seems like this is a layout issue, so I think any CSS conflicting or you may try to resize images.
What to do with error undefined array (column name)
Are you getting error after modification?
Hi Javed
Great shopping cart and thank you, I am just wondering if I want to display all products and add to shopping cart rather than view each product and add to cart. At the moment you have to do each product individually, in other word I don’t want go back home to chose another product and then add to card
Dear Hakim,
Yes it is possible but for this purpose, you will need to do many changes in it.
Javed, you got good PHP tutorials on here but can you please explain more on the code what it’s doing and why it’s doing that?.. For example, Why is session is having the database name shopping_cart inside when it suppose to be like an id, name, etc?..
Dear Tommy, Thanks for the suggestion, I will explain my code more in detail.
Thanks for the details
Thanks for the appreciation.
The Remove item isn’t working and even the css is not applied in my pages
I have the same issue.
Seems like you both have css href directory issue, make sure that css must be available in the same location where you are pointing to.
If remove button is not working then echo something when the remove is clicked so that you can debug the code, if pointer is going in there.
Ur code seems to have an error, it always shows I have an item in the cart and I cannot remove that item
Kindly make sure that your database must have alphanumeric item code.
Is it free to use?
Although, the purpose of my tutorials are to explain the basic functionalities of application. There are many other things that are required to do before make it publish on live environment. However, if you think that this is right for you so you can use it, but I will not be responsible if any error occurred because this tutorial was made for explanation purpose, not for using live environment, normally before implement it on live environment, people do some more validations and perform security operations.
This tutorial is really helpful
$cartArray = array(
$code=>array(
‘name’=>$name,
‘code’=>$code,
‘price’=>$price,
‘quantity’=>1,
‘image’=>$image)
);
Hi…I have a question regarding this array..the words in quotes are they the names of input fields or the name of database columns?…Thanks in Advance
Hi Kandy, this is the name of associative array, this is not name of input fields or database columns, you can change them anything you like.
Why do you have $code for two different variable?
Like here:
$code=>array(
and here:
‘code’=>$code,
One of them is array and one is having product code.
I have a query can u help me
Hi, sir.
How to add items to the cart without submitting (refresh) the page?
Well this feature is not available in it, but if you want so I can develop this application for you. I am available for freelance work.
Hello sir, can you help me. How to save the item in the cart into database. I want to save the order id, menu id, total price and quantity into database. Please help this is urgent.
You can use the following tutorial to store information into database here: https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
If you want to hire me for this task, email me here [email protected]
Hello sir,
I have this school project which requires us to use Ubuntu server and desktop to create a website of a shopping website ( which I feel that it is similar to this example). ( Creating a shopping website, creating cookies for Collation of information and tracking, Client side scripting using JavaScript for validation, Server-side scripting using PHP, Storage of information using MySQL database,Secure site development using digital certificates)
However, the teacher wants us to find more info online and he dosent really teach. All of the students dosent have any coding background ( my course is on the networking side). May I have some advices on how do I go about it for this project please? I am aware that w3school is a great place to start but I am the type of person who prefers to watch videos. Hence, I still feel kinda confusing when trying to learn from w3school. I do not really know what are the basics I need to know as there are so many things to learn in w3school and I feel overwhelmed.
I am very sorry for this lengthy message but I hope that you will give me some tips as you are a professional in this area. I will try my best to follow this example given as I find this example extremely useful.
Hello Sir, Im doing my term project on Slovak Technical Univerzity and using as help your tutorial. First of all it all works nicely but my teacher want to improve it a little more with this way -> : – to connect MySQL database with shopping cart, when I “buy” it, it will show me in MySQL table for “orders” the product what i want. And I dont know how to connect it. Can you help me please? I really appreciate that. Thank you.
Filip, student from Slovakia
Hello Javed, thank you for the code – it is just what i need! It works perfectly when the products codes are (Laptop01,Bags01 and iphone01)
But when i use only digits instead as codes (1,2,3), there is a bug in checking script for “Product is already added to your cart! You can add some products twice – as duplicated row in the cart, and then cant empty the cart from the duplicated item
….please check
Work this project with PHP 8.0?
I didn’t test it on PHP 8.0
Hi , thank you .
I need the image in one row , I have 9 image need every 3 image in one row .
just use bootstrap for that. It’ll make it a lot easier for you
Use Bootsrap Grid
for example,
This will solve your problem!!
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(
$id=>array(
“pid”=>$row[‘product_id’],
“name”=>$row[‘name’],
“price”=>$row[‘price’],
“image”=>$row[‘image’],
“qty”=>1
)
);
$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 {
$_SESSION[‘cartData’]
= 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..?
Dear Arjun, have you tested my code first before making any changes in it?
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).
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.
what I have to write in URL to see the result??
thank you
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.
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.
(URGENT MATTER)
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?
Dear Bernice, Sessions are very important here, we are temporary storing values in it and displaying them to the users.
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:
“.$row[‘name’].”
$”.$row[‘price’].”
Buy Now
May you help me to solve it!?
I am fetching data from database, is your db connection is working?
yes, db connection is working but it keep displaying that warning of undefined index
Well it should not give any error but if you are still getting it, make sure that there is no variable which is not defined but printing. This error caused by this reason commonly.
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.
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.
Sir, thank you.
You welcome 🙂
Please make another tutorial on complete checkout process .
It’s a very nice and simple tutorial but how can we get the details of add to cart products in database.
I think…You can get it by using $_SESSION variables.
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
ERR_CACHE_MISS
Do you know how to avoid this because it’s not giving a great UX 😉
I cant see anything, i have followed the correct steps even downloaded the zip file. My database is connected but nothing shows
please help!
I would suggest you to echo values from DB, if you are sure that you are connected then values must be printed on screen.
I’m facing the same problem likewise
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
Install XAMPP application on your computer.
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?????
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.
How can I add guest review and ratings?
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.
Man you are the Master thank you for this tutorial I really wish to see the fully operational cart though..
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?
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
Dear Rogue,
We simply check if there are any item listed / already added into the cart then display them.
How i want to put quantity field in this statement? in the index.php???
<?php
$result = mysqli_query($conn,"SELECT * FROM `products`");
while($row = mysqli_fetch_assoc($result)){
echo "
“.$row[‘name’].”
“.$row[‘description’].”
RM”.$row[‘price’].”
“.$row[‘quantity’].”
Buy Now
“;
}
?>
You do not need to enter quantity field, i have already added this feature on cart.php page. simply select quantity from dropdown.
That’s a wonderful tutorial
Thanks Edward 🙂
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
Dear Odwa,
First try to execute the sql in MySQL, debug there and if it is working fine then move ahead.
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?
Dear Nandhini, kindly share detail of error you are getting.
Sir ADD to Cart is Working well.
but next what we do.?
payment method + Complete order
Please make a tutorial
Dear Jillani, it is basic tutorial, sure i will create more tutorial about payment integration.
Great to know that Javed.. This is awesome!!! Thanks for all the efforts for sharing your knowledge.
Thanks for the appreciation.
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: AllPHPTricks.com”
Something i am missing perhaps??
Thank you.
Well if you download the complete tutorial via download link so you will get all images as well, just copy paste that tutorial and try to run it.
Thank you for the response, i downloaded the whole tutorial, Shopping cart is working fine but pictures still don’t display.
Right click on the image and open in new tab and check if these images are opening in new tab, this will also confirm you that file exist in that location or not.
Good work but what is the password for the encrypted file plz
There is no password on my tutorial file.
Sir please explain how to insert more than one cartid under same checkout id
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
Thank You for sharing your thoughts with us. ave really appreciated.
Thanks for the appreciation.
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
I have same promlem, are you slovet ?
Sir, I’m really appreciate and proud of you always because, your works solve a lot of my problem, finally you are my mentor.
Dear Muhammad Auwal Haruna,
Thanks for the appreciation.
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????
You’ve made it soo easy. I had to go through quite some YouTube tutorials to get all this info. Good work sir!
Thanks for the appreciation Kevin.
Thanks alot for this tutorial sir. it has been very helpful.
Thanks Alain Jr for the appreciation.
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!
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
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.
How to limit apply in this project
For i select 5 product so i want to show your cart is full
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.
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.
Hi Bonnie, thanks that you find tutorial helpful, if you want so you can hire me. contact me at my email [email protected] with title Freelance Project
sir i cant remove the items in the cart…its not working for me..can u help me
Anu try to download complete tutorial via download button and then set it up on your local host or live server. Check your PHP version as well.
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)
with
if($_POST[“code”] == $_SESSION[“shopping_cart”][$key][‘code’])
Thanks for your input.
Can u tell me how to add single product details page connection to cart page. I means single product details page pe add to cart button click so item added to cart
You will need to follow the same procedure which I used to add product into cart.
I tried to explain things as simple as possible. However, if you would like to hire me for the same task, send me your project complete details here [email protected]
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:
<?php
$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.
Make sure you are performing these checking after form submission, so make sure you are using isset() function before perform anything.
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
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?
You can learn here how to insert into database, https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
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
Either you haven’t declared the variable or you have missed the semicolon in the previous line of the declaration. Please once check with the declaration part
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?
Hi Bear, well in here it is working fine, you should try the code on both local and live environment and try to use XAMPP. I am also using XAMPP for local server.
Please sir I am using your code in my project. Can you help me with checkout process. How to checkout and move to Payment
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.
Hey can i use this script with php 7?
Yeah you can very well use!!
i cannot remove item from the cart when there more then 3
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
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.
I got the issue with merge array,
after adding the first item immediately array index starts from 0,1,2,… how to resolve it
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?
Please provide code for checkout and show that table in another page as final checkout output
This is just simple shopping cart, basically online shopping involves online payment to complete any shopping. So it vary what kind of payment method you are using.
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
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!
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.
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’
This tutorial is based on PHP sessions, make sure sessions are working fine there.
// 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
Yes Alex, you will get the error because you need to enter your host, user, password and database.
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)) {
exit(mysqli_error($this->db));
}
$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)) {
exit(mysqli_error($this->db));
}
$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) {
$i++;
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]);
}
}
?>
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
Make sure that Session is working fine at your server.
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
Hi Hamza, images or files are uploaded in server and their URL or address is stored in database so that you can link the address of image in tag src. You can check my tutorial about upload file or image here. https://www.allphptricks.com/upload-file-using-php-save-directory/
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.
Hi Simon, you can find these both in html form, which are hidden fields. These are used to identify that which form is submitted.
You provide very helpful code. Sir my query is How to work according to product varient. For example: price change according tshirt color.
you want to send parameter value as “change” in postman
eg:
if (isset($_POST[‘name’]) ==”change”)
in postman you should send
name:change
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.
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?
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.
How to execute this one
Sorry i didn’t get your question.
Good job brother
Thanks Edward
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?
Thanks!
You will need to create more input fields and store their values as well.
Can u suggest how i checkout all products
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.
Javed, how would the image be shown by being drawn from the database?
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.
My images are not shown eventhough I already uploaded the images in img folder in my host?How do I overcome this problem?
Check the image source url on webpage, make sure it is pointing to the right location with correct extension of image file.
Thanks a lot for your, its greate
You welcome Irfan.
How do I put more products into my database with a insert button on my website?
You will need to create a database query.
how to change the image size?
There are several ways to do so, you can use CSS or use small or large size images as per your need.
By using width and height, either in css or within style,
For example,
style=”width:45px;height:34px;”
or
img
{
width:34px;
height:45;
}
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 ”
“.$row[‘pname’].”
$”.$row[‘price’].”
Buy Now
“;
}
mysqli_close($connection);
?>
Check out your database connection first, if it is working fine then make sure you have inserted records in your table to fetch.
just a question.. who is that variable $con ? can i replace it in my code? Thank you, your work is great!
$con is a connection of database if you are changing it make sure you also change it in DB connection too.
It is possible to complete this script with a checkout module?
Well this is only for learning purpose, you will need to do more modification to make it complete.
And do your script have any pagination?
You can find pagination tutorial here https://www.allphptricks.com/create-simple-pagination-using-php-and-mysqli/
Wonderful job out there. Thank you
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?
Hi Celestine, purpose of this tutorial is to show the basic working of add to cart. Therefore i keep it simple as possible. For database insertion you can check out my other tutorial https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
Thanks a lot for your time and sharing your knowledge….
You welcome Alessandro and thanks for stopping by, if you found my tutorials helpful share them with your friends. 🙂