Simple Shopping Cart using Session in PHP Tutorial

Language

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.

  1. <?php
  2. //initialize cart if not set or is unset
  3. if(!isset($_SESSION['cart'])){
  4. $_SESSION['cart'] = array();
  5. }
  6.  
  7. //unset quantity
  8. unset($_SESSION['qty_array']);
  9. ?>
  10. <!DOCTYPE html>
  11. <html>
  12. <head>
  13. <meta charset="utf-8">
  14. <title>Simple Shopping Cart using Session in PHP</title>
  15. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  16. <style>
  17. .product_image{
  18. height:200px;
  19. }
  20. .product_name{
  21. height:80px;
  22. padding-left:20px;
  23. padding-right:20px;
  24. }
  25. .product_footer{
  26. padding-left:20px;
  27. padding-right:20px;
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div class="container">
  33. <nav class="navbar navbar-default">
  34. <div class="container-fluid">
  35. <div class="navbar-header">
  36. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  37. <span class="sr-only">Toggle navigation</span>
  38. <span class="icon-bar"></span>
  39. <span class="icon-bar"></span>
  40. <span class="icon-bar"></span>
  41. </button>
  42. <a class="navbar-brand" href="#">Simple Shopping Cart</a>
  43. </div>
  44.  
  45. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  46. <ul class="nav navbar-nav">
  47. <!-- left nav here -->
  48. </ul>
  49. <ul class="nav navbar-nav navbar-right">
  50. <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>
  51. </ul>
  52. </div>
  53. </div>
  54. </nav>
  55. <?php
  56. //info message
  57. if(isset($_SESSION['message'])){
  58. ?>
  59. <div class="row">
  60. <div class="col-sm-6 col-sm-offset-6">
  61. <div class="alert alert-info text-center">
  62. <?php echo $_SESSION['message']; ?>
  63. </div>
  64. </div>
  65. </div>
  66. <?php
  67. unset($_SESSION['message']);
  68. }
  69. //end info message
  70. //fetch our products
  71. //connection
  72. $conn = new mysqli('localhost', 'root', '', 'database');
  73.  
  74. $sql = "SELECT * FROM products";
  75. $query = $conn->query($sql);
  76. $inc = 4;
  77. while($row = $query->fetch_assoc()){
  78. $inc = ($inc == 4) ? 1 : $inc + 1;
  79. if($inc == 1) echo "<div class='row text-center'>";
  80. ?>
  81. <div class="col-sm-3">
  82. <div class="panel panel-default">
  83. <div class="panel-body">
  84. <div class="row product_image">
  85. <img src="<?php echo $row['photo'] ?>" width="80%" height="auto">
  86. </div>
  87. <div class="row product_name">
  88. <h4><?php echo $row['name']; ?></h4>
  89. </div>
  90. <div class="row product_footer">
  91. <p class="pull-left"><b><?php echo $row['price']; ?></b></p>
  92. <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>
  93. </div>
  94. </div>
  95. </div>
  96. </div>
  97. <?php
  98. }
  99. if($inc == 1) echo "<div></div><div></div><div></div></div>";
  100. if($inc == 2) echo "<div></div><div></div></div>";
  101. if($inc == 3) echo "<div></div></div>";
  102.  
  103. //end product row
  104. ?>
  105. </div>
  106. </body>
  107. </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.

  1. <?php
  2.  
  3. //check if product is already in the cart
  4. if(!in_array($_GET['id'], $_SESSION['cart'])){
  5. array_push($_SESSION['cart'], $_GET['id']);
  6. $_SESSION['message'] = 'Product added to cart';
  7. }
  8. else{
  9. $_SESSION['message'] = 'Product already in cart';
  10. }
  11.  
  12. header('location: index.php');
  13. ?>

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.

  1. <?php
  2. ?>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="utf-8">
  7. <title>Simple Shopping Cart using Session in PHP</title>
  8. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  9. </head>
  10. <body>
  11. <div class="container">
  12. <nav class="navbar navbar-default">
  13. <div class="container-fluid">
  14. <div class="navbar-header">
  15. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  16. <span class="sr-only">Toggle navigation</span>
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. </button>
  21. <a class="navbar-brand" href="#">Simple Shopping Cart</a>
  22. </div>
  23.  
  24. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  25. <ul class="nav navbar-nav">
  26. <!-- left nav here -->
  27. </ul>
  28. <ul class="nav navbar-nav navbar-right">
  29. <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>
  30. </ul>
  31. </div>
  32. </div>
  33. </nav>
  34. <h1 class="page-header text-center">Cart Details</h1>
  35. <div class="row">
  36. <div class="col-sm-8 col-sm-offset-2">
  37. <?php
  38. if(isset($_SESSION['message'])){
  39. ?>
  40. <div class="alert alert-info text-center">
  41. <?php echo $_SESSION['message']; ?>
  42. </div>
  43. <?php
  44. unset($_SESSION['message']);
  45. }
  46.  
  47. ?>
  48. <form method="POST" action="save_cart.php">
  49. <table class="table table-bordered table-striped">
  50. <thead>
  51. <th></th>
  52. <th>Name</th>
  53. <th>Price</th>
  54. <th>Quantity</th>
  55. <th>Subtotal</th>
  56. </thead>
  57. <tbody>
  58. <?php
  59. //initialize total
  60. $total = 0;
  61. if(!empty($_SESSION['cart'])){
  62. //connection
  63. $conn = new mysqli('localhost', 'root', '', 'database');
  64. //create array of initail qty which is 1
  65. $index = 0;
  66. if(!isset($_SESSION['qty_array'])){
  67. $_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
  68. }
  69. $sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
  70. $query = $conn->query($sql);
  71. while($row = $query->fetch_assoc()){
  72. ?>
  73. <tr>
  74. <td>
  75. <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>
  76. </td>
  77. <td><?php echo $row['name']; ?></td>
  78. <td><?php echo number_format($row['price'], 2); ?></td>
  79. <input type="hidden" name="indexes[]" value="<?php echo $index; ?>">
  80. <td><input type="text" class="form-control" value="<?php echo $_SESSION['qty_array'][$index]; ?>" name="qty_<?php echo $index; ?>"></td>
  81. <td><?php echo number_format($_SESSION['qty_array'][$index]*$row['price'], 2); ?></td>
  82. <?php $total += $_SESSION['qty_array'][$index]*$row['price']; ?>
  83. </tr>
  84. <?php
  85. $index ++;
  86. }
  87. }
  88. else{
  89. ?>
  90. <tr>
  91. <td colspan="4" class="text-center">No Item in Cart</td>
  92. </tr>
  93. <?php
  94. }
  95.  
  96. ?>
  97. <tr>
  98. <td colspan="4" align="right"><b>Total</b></td>
  99. <td><b><?php echo number_format($total, 2); ?></b></td>
  100. </tr>
  101. </tbody>
  102. </table>
  103. <a href="index.php" class="btn btn-primary"><span class="glyphicon glyphicon-arrow-left"></span> Back</a>
  104. <button type="submit" class="btn btn-success" name="save">Save Changes</button>
  105. <a href="clear_cart.php" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Clear Cart</a>
  106. <a href="checkout.php" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Checkout</a>
  107. </form>
  108. </div>
  109. </div>
  110. </div>
  111. </body>
  112. </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.

  1. <?php
  2.  
  3. //remove the id from our cart array
  4. $key = array_search($_GET['id'], $_SESSION['cart']);
  5. unset($_SESSION['cart'][$key]);
  6.  
  7. unset($_SESSION['qty_array'][$_GET['index']]);
  8. //rearrange array after unset
  9. $_SESSION['qty_array'] = array_values($_SESSION['qty_array']);
  10.  
  11. $_SESSION['message'] = "Product deleted from cart";
  12. header('location: view_cart.php');
  13. ?>

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.
  1. <?php
  2. if(isset($_POST['save'])){
  3. foreach($_POST['indexes'] as $key){
  4. $_SESSION['qty_array'][$key] = $_POST['qty_'.$key];
  5. }
  6.  
  7. $_SESSION['message'] = 'Cart updated successfully';
  8. header('location: view_cart.php');
  9. }
  10. ?>

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.

  1. <?php
  2. unset($_SESSION['cart']);
  3. $_SESSION['message'] = 'Cart cleared successfully';
  4. header('location: index.php');
  5. ?>

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.

  1. <?php
  2. //user needs to login to checkout
  3. $_SESSION['message'] = 'You need to login to checkout';
  4. header('location: view_cart.php');
  5. ?>

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

Submitted byzxcv (not verified)on Sun, 03/25/2018 - 04:04

That was smooth. Are you gonna include the user login for the tutorial? I would like to see your take on it. In the meanwhile, I'll try myself with login.
Submitted byrev1395 (not verified)on Sat, 11/23/2019 - 23:02

In reply to by zxcv (not verified)

Dude have you been able to make the user login work?

Yes! It would be fine to see the code with the log in.
Submitted byDsk (not verified)on Mon, 12/05/2022 - 06:36

Why do you have it that you can add only 1 item per time how can i make it when you add the same item the quantity goes +1

Add new comment