Table of Contents
Tutorial: Simple Shopping Cart using Session in PHP with Source Code
Getting Started
This is Simple Shopping Cart using Session in PHP tutorial. I’ve used Bootstrap in this tutorial which is a CSS framework and is included in the downloadable of this tutorial, but if you want, you may download Bootstrap using this link.
Creating a Database
Next, we are going to create our database which contains the sample product that we are going to show.
I’ve included a .sql file in the downloadable of this tutorial which is a MySQL database file. All you have to do is import the said file. If you have no idea on how to do this, please refer to my tutorial.
You should be able to create a database with tables named database.
Related Projects: Online Shopping Portal, Online Shopping System
Displaying a Products
Next, we create the page to display products to our user. We do this by creating a new file, name it as index.php and paste the codes below.
<?php session_start(); //initialize cart if not set or is unset if(!isset($_SESSION['cart'])){ $_SESSION['cart'] = array(); } //unset quantity unset($_SESSION['qty_array']); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple Shopping Cart using Session in PHP</title> <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"> <style> .product_image{ height:200px; } .product_name{ height:80px; padding-left:20px; padding-right:20px; } .product_footer{ padding-left:20px; padding-right:20px; } </style> </head> <body> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <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="#">Simple Shopping Cart</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <!-- left nav here --> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="view_cart.php"><span class="badge"><?php echo count($_SESSION['cart']); ?></span> Cart <span class="glyphicon glyphicon-shopping-cart"></span></a></li> </ul> </div> </div> </nav> <?php //info message if(isset($_SESSION['message'])){ ?> <div class="row"> <div class="col-sm-6 col-sm-offset-6"> <div class="alert alert-info text-center"> <?php echo $_SESSION['message']; ?> </div> </div> </div> <?php unset($_SESSION['message']); } //end info message //fetch our products //connection $conn = new mysqli('localhost', 'root', '', 'database'); $sql = "SELECT * FROM products"; $query = $conn->query($sql); $inc = 4; while($row = $query->fetch_assoc()){ $inc = ($inc == 4) ? 1 : $inc + 1; if($inc == 1) echo "<div class='row text-center'>"; ?> <div class="col-sm-3"> <div class="panel panel-default"> <div class="panel-body"> <div class="row product_image"> <img src="<?php echo $row['photo'] ?>" width="80%" height="auto"> </div> <div class="row product_name"> <h4><?php echo $row['name']; ?></h4> </div> <div class="row product_footer"> <p class="pull-left"><b><?php echo $row['price']; ?></b></p> <span class="pull-right"><a href="add_cart.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm"><span class="glyphicon glyphicon-plus"></span> Cart</a></span> </div> </div> </div> </div> <?php } if($inc == 1) echo "<div></div><div></div><div></div></div>"; if($inc == 2) echo "<div></div><div></div></div>"; if($inc == 3) echo "<div></div></div>"; //end product row ?> </div> </body> </html>
Creating a Add-to-Cart Script
Next, we are going to create our add to cart script which will add to our cart which is the form of PHP session.
Create a new file, name it as add_cart.php and paste the codes below.
<?php session_start(); //check if product is already in the cart if(!in_array($_GET['id'], $_SESSION['cart'])){ array_push($_SESSION['cart'], $_GET['id']); $_SESSION['message'] = 'Product added to cart'; } else{ $_SESSION['message'] = 'Product already in cart'; } header('location: index.php'); ?>
Creating a View-Cart Page
Next, we create a page where the user can view his cart. Create a new file, name it as view_cart.php and paste the codes below.
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple Shopping Cart using Session in PHP</title> <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"> </head> <body> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <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="#">Simple Shopping Cart</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <!-- left nav here --> </ul> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="view_cart.php"><span class="badge"><?php echo count($_SESSION['cart']); ?></span> Cart <span class="glyphicon glyphicon-shopping-cart"></span></a></li> </ul> </div> </div> </nav> <h1 class="page-header text-center">Cart Details</h1> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <?php if(isset($_SESSION['message'])){ ?> <div class="alert alert-info text-center"> <?php echo $_SESSION['message']; ?> </div> <?php unset($_SESSION['message']); } ?> <form method="POST" action="save_cart.php"> <table class="table table-bordered table-striped"> <thead> <th></th> <th>Name</th> <th>Price</th> <th>Quantity</th> <th>Subtotal</th> </thead> <tbody> <?php //initialize total $total = 0; if(!empty($_SESSION['cart'])){ //connection $conn = new mysqli('localhost', 'root', '', 'database'); //create array of initail qty which is 1 $index = 0; if(!isset($_SESSION['qty_array'])){ $_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1); } $sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")"; $query = $conn->query($sql); while($row = $query->fetch_assoc()){ ?> <tr> <td> <a href="delete_item.php?id=<?php echo $row['id']; ?>&index=<?php echo $index; ?>" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash"></span></a> </td> <td><?php echo $row['name']; ?></td> <td><?php echo number_format($row['price'], 2); ?></td> <input type="hidden" name="indexes[]" value="<?php echo $index; ?>"> <td><input type="text" class="form-control" value="<?php echo $_SESSION['qty_array'][$index]; ?>" name="qty_<?php echo $index; ?>"></td> <td><?php echo number_format($_SESSION['qty_array'][$index]*$row['price'], 2); ?></td> <?php $total += $_SESSION['qty_array'][$index]*$row['price']; ?> </tr> <?php $index ++; } } else{ ?> <tr> <td colspan="4" class="text-center">No Item in Cart</td> </tr> <?php } ?> <tr> <td colspan="4" align="right"><b>Total</b></td> <td><b><?php echo number_format($total, 2); ?></b></td> </tr> </tbody> </table> <a href="index.php" class="btn btn-primary"><span class="glyphicon glyphicon-arrow-left"></span> Back</a> <button type="submit" class="btn btn-success" name="save">Save Changes</button> <a href="clear_cart.php" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Clear Cart</a> <a href="checkout.php" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Checkout</a> </form> </div> </div> </div> </body> </html>
Creating a Delete Item Script
Next, we are going to create the script that removes item/s from the visitor’s cart. Create a new file, name it as delete_item.php and paste the codes below.
<?php session_start(); //remove the id from our cart array $key = array_search($_GET['id'], $_SESSION['cart']); unset($_SESSION['cart'][$key]); unset($_SESSION['qty_array'][$_GET['index']]); //rearrange array after unset $_SESSION['qty_array'] = array_values($_SESSION['qty_array']); $_SESSION['message'] = "Product deleted from cart"; header('location: view_cart.php'); ?>
Creating a Update Quantity Script
Initially, we have defined the quantities of added products to cart by 1. If ever the visitor wants to edit the quantity and saves it, this is the script that we are going to use.
Create a new file, name it as save_cart.php and paste the codes below.
<?php session_start(); if(isset($_POST['save'])){ foreach($_POST['indexes'] as $key){ $_SESSION['qty_array'][$key] = $_POST['qty_'.$key]; } $_SESSION['message'] = 'Cart updated successfully'; header('location: view_cart.php'); } ?>
Creating a remove-the-entire-cart Script
Next, we are going to create a script that whenever the visitor wants to clear his cart, the cart will reset.
Create a new file, name it as clear_cart.php and paste the codes below.
<?php session_start(); unset($_SESSION['cart']); $_SESSION['message'] = 'Cart cleared successfully'; header('location: index.php'); ?>
Creating a Checkout Redirection
Lastly, we create the script that will redirect our visitor if he clicks the checkout button which supposed to lead him to the login page but in this tutorial, we are going to create a simple message to our visitor.
Create a new file, name it as checkout.php and paste the codes below.
<?php session_start(); //user needs to login to checkout $_SESSION['message'] = 'You need to login to checkout'; header('location: view_cart.php'); ?>