Simple Shopping Cart using Session in PHP Tutorial
This tutorial tackles on how to create a simple shopping cart using session in PHP. This tutorial is intended before the user actually logged into your e-commerce site. It would be a different story if the user logged into the system since where are going to use its user id for the cart of the specific user.
Getting Started
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 our 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 how to do this, please refer to my tutorial, https://www.sourcecodester.com/tutorials/sql/12049/how-import-sql-file-restore-mysql-database.html.
You should be able to create a database with tables named database. Note copy the images folder too and paste it in your source code root folder. The images folder is for sample product images.
Displaying our Products
Next, we create a page to display products to our users. We do this by creating a new file, name it as index.php and paste the codes below.
- <?php
- //initialize cart if not set or is unset
- }
- //unset quantity
- ?>
- <!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
- ?>
- <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
- }
- //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 our 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
- //check if product is already in the cart
- $_SESSION['message'] = 'Product added to cart';
- }
- else{
- $_SESSION['message'] = 'Product already in cart';
- }
- ?>
Creating our 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
- ?>
- <!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
- ?>
- <div class="alert alert-info text-center">
- <?php echo $_SESSION['message']; ?>
- </div>
- <?php
- }
- ?>
- <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;
- //connection
- $conn = new mysqli('localhost', 'root', '', 'database');
- //create array of initail qty which is 1
- $index = 0;
- }
- $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>
- <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>
- <?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>
- </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 our 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
- //remove the id from our cart array
- //rearrange array after unset
- $_SESSION['message'] = "Product deleted from cart";
- ?>
Creating our Update Quantity Script
Initially, we have defined the quantities of added products to the 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
- foreach($_POST['indexes'] as $key){
- $_SESSION['qty_array'][$key] = $_POST['qty_'.$key];
- }
- $_SESSION['message'] = 'Cart updated successfully';
- }
- ?>
Creating our 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['message'] = 'Cart cleared successfully';
- ?>
Creating our 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 for our visitor.
Create a new file, name it as checkout.php and paste the codes below.
- <?php
- //user needs to login to checkout
- $_SESSION['message'] = 'You need to login to checkout';
- ?>
That ends this tutorial. I hope this will help you and you have learned something useful for your future projects. Explore more on this website for more tutorials and free project source code.
Happy Coding :)Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
Comments
Store session cart into database
Why do you have it that you…
Add new comment
- Add new comment
- 26370 views