In this tutorial, we are going to create a Simple Shopping Cart using PHP and MySQL. The purpose of this tutorial is to tell the basic concept of a shopping cart and how to use PHP sessions to store values into an array of the cart.
eCommerce websites usually use the PHP session to store items that are added by the user into a cart.
What is a Shopping Cart?
On the internet the shopping cart is an online application which is available on the internet on e-commerce websites, the buyers on the website can choose and add different items into a cart which they are interested in buying online.
So let’s begin creating a simple shopping cart using MySQLi and PHP.
Steps for Creating a Simple Shopping Cart Using MySQLi and PHP
I have divided this tutorial into some steps to make it easier to understand its working.
- Creating a Database, Table and Dump Sample Data
- Create a Database Connection
- Creating an Index File
- Create a Cart File
- Creating a CSS File
1. Creating Database, Table and Dump Sample Data
To create database run the following query in MySQL.
CREATE DATABASE allsweb;
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 attached the SQL file of this table with dummy data; download the complete zip file of this tutorial.
2. Create a Database Connection
After that, create a db.php file and paste the given database connection in it. Make sure that you update your credentials with these database credentials.
// Enter your Host, username, password, database below. $con = mysqli_connect("localhost","root","","allsweb"); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); die();
3. Creating an Index File
After that, create an index.php file and paste the bellow script at 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 only adding values of selected items into the array so that we can display them into the cart.php page.
Add the given script in the same file in the 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 below script in the same file after adding the above text to display products from the database and display a 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. Creating a Cart File
Now, create a cart.php file and paste the given script at the beginning of the 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 tasks based on the chosen action. If the user clicks on the remove item button, it will remove the item from the cart. And if the user changes the selected item quantity, it will also update the item quantity in the session array if you want to show the cart icon here so you may do the same, which we did before in index.php file.
Insert the given 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 merely displaying the products with full details, its price, units, image, and total amount. Here users can also select the number of its products. All messages of adding and removing quantity will also display here at the bottom. A sample screenshot is also attached below:
5. Creating a CSS File
At last, create a 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; }
If you found this tutorial helpful, share it with your friends, developers groups, and leave your comment.
Also, read our previous blog- Insert, View, Edit and Delete Record from Database Using MySQLi and PHP