If you want to build your own online shopping cart from scratch, this post can help you get it done because today, we are building a simple website with shopping cart using PHP and MySQL. I also assume you already know something about PHP sessions.
![]() |
Our shopping cart's product page. |
Our simple system will have three pages.
- Home Page - the landing page, you can also show your products here, but in our example, we will just display a welcome message.
- Products Page - shows your list of products with the option "add to cart" - cart icon with plus (+) sign.
- Cart Page - shows the list of products the user added to his cart. It has the option to "remove from cart " - cart icon with dash (-) sign.
Code used in this post is available for download and live demo:
Preparing our Database
SQL table we used.
libs/DbConnect.php - will help us connect to the database.
CREATETABLEIF NOT EXISTS `products` (
`id`int(11) NOT NULL AUTO_INCREMENT,
`name`varchar(32) NOT NULL,
`price`int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `products`
--
INSERT INTO`products` (`id`, `name`, `price`) VALUES
(1, 'LG P880 4X HD', 336),
(2, 'Google Nexus 4', 299),
(3, 'Samsung Galaxy S4', 600);
libs/DbConnect.php - will help us connect to the database.
Navigation
Navigation.php - contains the nagivation links to the home, products and cart page. This file is included to the main sections of our system.
<?php
// to count items in the cart
$cartItemCount=count($_SESSION['cart']);
?>
<divclass='navigation'>
<ahref='index.php'class='customButton'>Home</a>
<ahref='Products.php'class='customButton'>View Products</a>
<ahref='Cart.php'class='customButton'>View Cart <?php echo"({$cartItemCount})"; ?></a>
</div>
Welcoming Online Shoppers
Index.php - your customers or online shoppers should feel welcome to your site. I don't know how you design this but the code below is just a very simple example.<?php
session_start();
?>
<html>
<head>
<title>php shopping cart tutorial - home - codeofaninja.com</title>
<linktype="text/css"rel="stylesheet"href="css/style.css" />
</head>
<body>
<divclass='sectionContainer'>
<divclass='sectionHeader'>Home</div>
<?php
// this will make 'home', 'view products' and 'view cart' appear
include'Navigation.php'
?>
<divclass='sectionContents'>
Welcome to Mike's shopping website!
</div>
</div>
</body>
</html>
Listing Your Products
Products.php - lists products from our database.<?php
session_start();
?>
<html>
<head>
<title>php shopping cart tutorial - products - codeofaninja.com</title>
<linktype="text/css"rel="stylesheet"href="css/style.css" />
</head>
<body>
<divclass='sectionContainer'>
<divclass='sectionHeader'>Products</div>
<?php
// this will make 'home', 'view products' and 'view cart' appear
include'Navigation.php'
?>
<divclass='sectionContents'>
<?php
if($_GET['action']=='add'){
echo"<div>".$_GET['name'] ." was added to your cart.</div>";
}
if($_GET['action']=='exists'){
echo"<div>".$_GET['name'] ." already exists in your cart.</div>";
}
require"libs/DbConnect.php";
$query="SELECT id, name, price FROM products";
$stmt=$con->prepare( $query );
$stmt->execute();
$num=$stmt->rowCount();
if($num>0){
echo"<table border='0'>";//start table
// our table heading
echo"<tr>";
echo"<th class='textAlignLeft'>Product Name</th>";
echo"<th>Price (USD)</th>";
echo"<th>Action</th>";
echo"</tr>";
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo"<tr>";
echo"<td>{$name}</td>";
echo"<td class='textAlignRight'>{$price}</td>";
echo"<td class='textAlignCenter'>";
echo"<a href='addToCart.php?id={$id}&name={$name}' class='customButton'>";
echo"<img src='images/add-to-cart.png' title='Add To Cart' />";
echo"</a>";
echo"</td>";
echo"</tr>";
}
echo"</table>";
}
// no products in the database
else{
echo"No products found.";
}
?>
</div>
</div>
</body>
</html>
Adding Products To Cart
AddToCart.php - adds the product ID to the 'cart' session array. It also checks if the ID is already added in the session to prevent duplicate products in the cart. This file is triggered when the user clicked the 'add to cart' icon.<?php
session_start();
// get the product id
$id=$_GET['id'];
$name=$_GET['name'];
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] =array();
}
// check if the item is in the array, if it is, do not add
if(in_array($id, $_SESSION['cart'])){
// redirect to product list and tell the user it was added to cart
header('Location: Products.php?action=exists&id'.$id.'&name='.$name);
}
// else, add the item to the array
else{
array_push($_SESSION['cart'], $id);
// redirect to product list and tell the user it was added to cart
header('Location: Products.php?action=add&id'.$id.'&name='.$name);
}
?>
Listing Products in the Cart
Cart.php - lists products added to the users' cart.<?php
session_start();
?>
<html>
<head>
<title>php shopping cart tutorial - cart - codeofaninja.com</title>
<linktype="text/css"rel="stylesheet"href="css/style.css" />
</head>
<body>
<divclass='sectionContainer'>
<divclass='sectionHeader'>Shopping Cart</div>
<?php
// this will make 'home', 'view products' and 'view cart' appear
include'Navigation.php'
?>
<divclass='sectionContents'>
<?php
if($_GET['action']=='removed'){
echo"<div>".$_GET['name'] ." was removed from cart.</div>";
}
if(isset($_SESSION['cart'])){
$ids="";
foreach($_SESSION['cart'] as$id){
$ids=$ids.$id.",";
}
// remove the last comma
$ids=rtrim($ids, ',');
require"libs/DbConnect.php";
$query="SELECT id, name, price FROM products WHERE id IN ({$ids})";
$stmt=$con->prepare( $query );
$stmt->execute();
$num=$stmt->rowCount();
if($num>0){
echo"<table border='0'>";//start table
// our table heading
echo"<tr>";
echo"<th class='textAlignLeft'>Product Name</th>";
echo"<th>Price (USD)</th>";
echo"<th>Action</th>";
echo"</tr>";
//also compute for total price
$totalPrice=0;
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$totalPrice+=$price;
//creating new table row per record
echo"<tr>";
echo"<td>{$name}</td>";
echo"<td class='textAlignRight'>{$price}</td>";
echo"<td class='textAlignCenter'>";
echo"<a href='removeFromCart.php?id={$id}&name={$name}' class='customButton'>";
echo"<img src='images/remove-from-cart.png' title='Remove from cart' />";
echo"</a>";
echo"</td>";
echo"</tr>";
}
echo"<tr>";
echo"<th class='textAlignCenter'>Total Price</th>";
echo"<th class='textAlignRight'>{$totalPrice}</th>";
echo"<th></th>";
echo"</tr>";
echo"</table>";
echo"<br /><div><a href='#' class='customButton'>Checkout</a></div>";
}else{
echo"<div>No products found in your cart. :(</div>";
}
}else{
echo"<div>No products in cart yet.</div>";
}
?>
</div>
</div>
</body>
</html>
Removing Products From Cart
RemoveFromCart.php - removes product ID the 'cart' session array. This file is triggered when the user clicked the 'remove from cart' icon.<?php
session_start();
// get the product id
$id=$_GET['id'];
$name=$_GET['name'];
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] =array();
}
// remove the item from the array
$_SESSION['cart'] =array_diff($_SESSION['cart'], array($id));
// redirect to product list and tell the user it was added to cart
header('Location: Cart.php?action=removed&id='.$id.'&name='.$name);
?>
Styling Our Online Shop
css/style.css - to make our simple system user friendly.body{
font:1em"Lucida Grande", Tahoma, Verdana, sans-serif;
color:#404040;
}
.navigation{
padding:1em;
}
.sectionContents{
padding:01em1em1em;
}
.sectionContentstable{
width:100%;
}
.sectionContentstableth{
padding:0.5em;
background-color:#f3f3f3;
}
.sectionContentstabletd{
padding:0.5em;
background-color:#f3f3f3;
}
.sectionContainer{
text-align:center;
border:thinsolid#000;
width:30em;
margin:7emauto0auto;
}
.sectionHeader{
font-size:1.5em;
border-bottom:thinsolidgray;
padding:10px;
background:#f3f3f3;
}
.textAlignCenter{
text-align:center;
}
.textAlignLeft{
text-align:left;
}
.textAlignRight{
text-align:right;
}
.customButton {
padding:5px;
-moz-box-shadow:inset0px1px0px0px#bbdaf7;
-webkit-box-shadow:inset0px1px0px0px#bbdaf7;
box-shadow:inset0px1px0px0px#bbdaf7;
background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
background:-moz-linear-gradient( centertop, #79bbff5%, #378de5100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
background-color:#79bbff;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1pxsolid#84bbf3;
display:inline-block;
color:#ffffff;
font-family:arial;
font-size:15px;
font-weight:bold;
text-decoration:none;
text-shadow:1px1px0px#528ecc;
cursor:pointer;
}
.customButton:hover {
background:-webkit-gradient( linear, lefttop, leftbottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
background:-moz-linear-gradient( centertop, #378de55%, #79bbff100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
background-color:#378de5;
}
.customButton:active {
position:relative;
top:1px;
}
Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code. :)