Home / PHP /

PHP Code – Shopping Cart System Tutorial using SESSIONS

PHP Shopping Cart Tutorial Using Sessions

If you want to build your own online shopping cart from scratch, we have good news for you! This post can help you get it done because we will build a simple shopping cart script today. We will use PHP, MySQL and PHP sessions to complete this task.

A lot of people use a ready-made software for this. But for coders like us, it is important to know how it was done so that we can create more features like making the system more secured, add some unique functionality, etc.

Our simple system will have two pages.

1. The products page (products.php) shows your list of products retrieved from the database. For each product, it has a blue button that says “Add to cart”, it also has a cart icon.

2. The cart page (cart.php) shows the list of products the user added to his cart. For each cart item, it has a red button that says “Remove from cart” with an “x” icon.

Our post will cover the following contents:

1.0 Code Output Demo
2.0 Files Overview
3.0 Step By Step Programming (Steps 1-10)
4.0 Enter or Update Cart Item Quantity
5.0 Download Source Code

1.0 Code Output Demo

Live demo link is provided below the video.

LIVE DEMO

Here’s another shopping cart script demo, with the update quantity feature. Live demo link is provided below the video.

LIVE DEMO

2.0 Files Overview of PHP Shopping Cart Tutorial

The files overview is useful for reminding ourselves which file or part of the script are we working on. Here’s an overview of the files used in this tutorial.

files and folders for php shopping cart tutorial with cookies

Let me explain what is the use of each files and folders above.

3.1 config is a folder that contains another file called db_connect.php which is the file used to connect to the MySQL database for retrieving product information.

3.2 add_to_cart.php is executed when the user clicks on the “add to cart” button. It processes the product data by adding it to the SESSION array variable to make it a cart item.

3.3 cart.php is where the cart items are read and displayed to the user. We retrieve the items from the SESSION array variable and loop through it to be displayed on an HTML table.

3.4 layout_foot.php is used as a closing HTML wrapper, and is included at the end of cart.php and products.php because it closes the tags started by layout_head.php, it also contains any JavaScript source and jQuery codes used in this script.

3.5 layout_head.php is used as an opening HTML page wrapper. It is included at the beginning of cart.php and products.php because it contains the opening HTML tag, head tags, title tags and any CSS resource used.

3.6 navigation.php contains the links to products.php and cart.php pages that the user can click. The cart item count is also shown here, beside the “Cart” link.

3.7 products.php displays all the products retrieve from the database. We are using PDO extension to connect and retrieve data from the MySQL database.

3.8 remove_from_cart.php is executed when the user clicks on the “Remove from cart” button. It removes the product item from the SESSION array variable.

Important note: This source code focuses on using PHP sessions for storing shopping cart items, the “checkout” is not in its scope.

3.0 Step By Step Programming

Now here’s the fun part.

Step 1: In your PhpMyAdmin, create a database and run the following SQL queries to create the sample tables.

CREATE TABLE IF 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);

Step 2: In your chosen root directory, create a folder named config.

Step 3: Inside that config folder, create a file named db_connect.php, and put the following code inside it, just change to database credentials to your own.

<?php
$host = "your_host";
$db_name = "your_database_name";
$username = "your_database_username";
$password = "your_database_password";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

Step 4: Create a file called products.php, we will retrieve the products using the code below.

<?php
session_start();

$page_title="Products";
include 'layout_head.php';

// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "1";
$name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='added'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> was added to your cart!";
	echo "</div>";
}

if($action=='exists'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> already exists in your cart!";
	echo "</div>";
}

$query = "SELECT id, name, price FROM products ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();

$num = $stmt->rowCount();

if($num>0){

	//start table
	echo "<table class='table table-hover table-responsive table-bordered'>";

        // 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>";
					echo "<div class='product-id' style='display:none;'>{$id}</div>";
					echo "<div class='product-name'>{$name}</div>";
				echo "</td>";
				echo "<td>&#36;{$price}</td>";
				echo "<td>";
					echo "<a href='add_to_cart.php?id={$id}&name={$name}' class='btn btn-primary'>";
						echo "<span class='glyphicon glyphicon-shopping-cart'></span> Add to cart";
					echo "</a>";
				echo "</td>";
            echo "</tr>";
        }

    echo "</table>";
}

// tell the user if there's no products in the database
else{
    echo "No products found.";
}

include 'layout_foot.php';
?>

Step 5: products.php on step 4 above will not actually work without the layout_head.php and layout_foot.php, so first, we’ll create the layout_head.php with the following code:

<?php
// connect to database
include 'config/db_connect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?> - LIVE DEMO</title>

    <!-- Bootstrap -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>
<body>

	<?php include 'navigation.php'; ?>

    <!-- container -->
    <div class="container">

        <div class="page-header">
            <h1><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?></h1>
        </div>

Step 6: layout_head.php includes another PHP file called navigation.php. We’ll create the navigation.php file and put the following code.

<!-- navbar -->
<div class="navbar navbar-default navbar-static-top" role="navigation">
	<div class="container">

		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
			<span class="sr-only">Toggle navigation</span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="products.php">Your Site</a>
		</div>

		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav">
				<li <?php echo $page_title=="Products" ? "class='active'" : ""; ?> >
					<a href="products.php">Products</a>
				</li>
				<li <?php echo $page_title=="Cart" ? "class='active'" : ""; ?> >
					<a href="cart.php">
						<?php
						// count products in cart
						$cart_count=count($_SESSION['cart_items']);
						?>
						Cart <span class="badge" id="comparison-count"><?php echo $cart_count; ?></span>
					</a>
				</li>
			</ul>
		</div><!--/.nav-collapse -->

	</div>
</div>
<!-- /navbar -->

Step 7: Now we’ll create the layout_foot.php file with the code below.

	</div>
	<!-- /container -->

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

</body>
</html>

Step 8: products.php has links to the add_to_cart.php file. We’ll create that add_to_cart.php file and put the code below.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart_items'])){
	$_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
	// 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{
	$_SESSION['cart_items'][$id]=$name;

	// redirect to product list and tell the user it was added to cart
	header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>

Step 9: Now if the products were able to be added on the cart, we’ll have to view it using cart.php. We’ll create that cart.php file with the following codes.

<?php
session_start();

$page_title="Cart";
include 'layout_head.php';

$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='removed'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> was removed from your cart!";
	echo "</div>";
}

else if($action=='quantity_updated'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> quantity was updated!";
	echo "</div>";
}

if(count($_SESSION['cart_items'])>0){

	// get the product ids
	$ids = "";
	foreach($_SESSION['cart_items'] as $id=>$value){
		$ids = $ids . $id . ",";
	}

	// remove the last comma
	$ids = rtrim($ids, ',');

	//start table
	echo "<table class='table table-hover table-responsive table-bordered'>";

        // our table heading
        echo "<tr>";
            echo "<th class='textAlignLeft'>Product Name</th>";
            echo "<th>Price (USD)</th>";
			echo "<th>Action</th>";
        echo "</tr>";

		$query = "SELECT id, name, price FROM products WHERE id IN ({$ids}) ORDER BY name";

		$stmt = $con->prepare( $query );
		$stmt->execute();

		$total_price=0;
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);

			echo "<tr>";
				echo "<td>{$name}</td>";
				echo "<td>&#36;{$price}</td>";
				echo "<td>";
					echo "<a href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-danger'>";
						echo "<span class='glyphicon glyphicon-remove'></span> Remove from cart";
					echo "</a>";
				echo "</td>";
            echo "</tr>";

			$total_price+=$price;
		}

		echo "<tr>";
				echo "<td><b>Total</b></td>";
				echo "<td>&#36;{$total_price}</td>";
				echo "<td>";
					echo "<a href='#' class='btn btn-success'>";
						echo "<span class='glyphicon glyphicon-shopping-cart'></span> Checkout";
					echo "</a>";
				echo "</td>";
            echo "</tr>";

	echo "</table>";
}

else{
	echo "<div class='alert alert-danger'>";
		echo "<strong>No products found</strong> in your cart!";
	echo "</div>";
}

include 'layout_foot.php';
?>

Step 10: cart.php links to a file called remove_from_cart.php to remove an item from the cart. We’ll create remove_from_cart.php with the codes below.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

// remove the item from the array
unset($_SESSION['cart_items'][$id]);

// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id . '&name=' . $name);
?>

4.0 Enter or Update Cart Item Quantity

The tutorial above only allows you to add, remove and compute the total price of items in the cart. It’s already very useful because the code shows you how to create, read, update and delete data in web cookies.

But what if your users want to enter or update the quantity of items in the cart? Is it possible using cookies? The good news is yes, it can be done. I will give you a basic idea on how I did it, see 4.1 to 4.3 below.

I did not include it in the code above because the simplicity of the tutorial will gone. I want it to be comprehensible even for beginners.

4.1 Add a new column named “Quantity” in products.php and cart.php. The word “Quantity” will be the column header and for the rest of the table row, it will be input or text boxes where the user can enter the product quantity before clicking the “Add to cart” or “Update cart” button.

4.2 On products.php, the “Add to cart” button will not be a direct link to add_to_cart.php file. It will be a button that will execute a jQuery code because it has to get the quantity entered by the user.

4.3 On cart.php, there will be an “Update cart” button beside the quantity textbox. Clicking it will run a jQuery script that gets the new quantity entered by the user and saves the changes with the help of a new file called “update_quantity.php”.

After doing my advice above, your output should look like this: LIVE DEMO

It looks simple to do, right? You can understand it more if you will see the complete source code. Please download it below so that you will get exactly what I mean and how I did it.

5.0 Source Code Download

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:
✔ Value or skill upgrade it can bring you, or
✔ Income you can get from your website project or business.
✔ For a limited time, I will give you the source code for a low price.

DOWNLOAD THE SOURCE CODE by clicking the BUY button below.

✔ You can get all the PHP files.
✔ Basic shopping cart script.
✔ The one with the update quantity feature.
✔ Free code updates.
✔ Free email support from me as well.

Download the source code by clicking the BUY button below.

Thanks for your support, it keeps this website alive!

6.0 Related Source Codes

6.1PHP Shopping Cart Tutorial Using COOKIES

6.2PHP and MySQL CRUD Tutorial for Beginners

6.3PHP Object Oriented CRUD Example with Bootstrap

Notes:

For those having some issues about the $conn variable, I highly recommend learning about PHP CRUD first. It will help you a lot.

Some of you are having a little issues fixing the undefined index notice. I updated the code above and download link to help you fix it, please try it and tell us in the comments section if it works or not. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code. :)

Loading comments...