Simple Shopping Cart with PHP and MySQL

A beginner-friendly, step-by-step tutorial that builds a shopping cart with plain PHP 5.6 and MySQL, storing the cart contents in a PHP session. It covers connecting to the database, listing products, adding items to the cart, and removing them — a solid starting point before building something more complex.

Shopping cart built with PHP and MySQL

📁 Step 1: Project Structure

Here's an overview of the files and folders used in this project:

Folder structure of the PHP shopping cart project
  • styles.css — Custom styles
  • app.js — JavaScript functions
  • jquery.1.11.2.min.js — jQuery library
  • /bootstrap-3.3.5/ — Bootstrap assets
  • /images/ — Product images
  • create-products.sql — SQL file for the products table
  • cart.php — Cart view and logic
  • shopping-cart.php — Product listing and add-to-cart

🛠️ Step 2: Connect to the MySQL Database

Configure your PHP file to connect to your MySQL database like this:

<?php //Config authentication with database $conn = new PDO("mysql:host=localhost;dbname=demo_cart_php", 'root', ''); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?>

🛒 Step 3: Add Products to the Cart

Main file PHP: shopping-cart.php
Given below our full PHP code, copy to use it.

When the user presses the "Add to shopping cart" button, the product details are saved in the shopping cart session with its SKU and other details. The following code handles the add-to-cart action and stores the product in the shopping cart session. If we click on the same product several times, the quantity will increase.

<?php //get action string $action = isset($_GET['action'])?$_GET['action']:""; //Conditional to add an added product to the basket if($action=='addcart' && $_SERVER['REQUEST_METHOD']=='POST') { //Finding the product by code $query = "SELECT * FROM products WHERE sku=:sku"; $stmt = $conn->prepare($query); $stmt->bindParam('sku', $_POST['sku']); $stmt->execute(); $product = $stmt->fetch(); $currentQty = $_SESSION['products'][$_POST['sku']]['qty']+1; //Incrementing the product qty in cart $_SESSION['products'][$_POST['sku']] =array('qty'=>$currentQty,'name'=>$product['name'],'image'=>$product['image'],'price'=>$product['price']); $product=''; header("Location:shopping-cart.php"); } //Empty all the shopping cart if($action=='emptyall') { $_SESSION['products'] =array(); header("Location:shopping-cart.php"); } //Empty product one by one if($action=='empty') { $sku = $_GET['sku']; $products = $_SESSION['products']; unset($products[$sku]); $_SESSION['products']= $products; header("Location:shopping-cart.php"); } //Get all Products $query = "SELECT * FROM products"; $stmt = $conn->prepare($query); $stmt->execute(); $products = $stmt->fetchAll(); ?>

🗂️ Step 4: Display Products from MySQL

Main file PHP: shopping-cart.php
Given below our full HTML code, copy to use it. This markup lists the products stored in the database, each with its description, price and name, plus an "Add To Cart" button.

<div class="container"> <?php if(!empty($_SESSION['products'])):?> <div class="alert alert-success" role="alert"><i class="fa fa-cart-plus"></i> <a href="cart.php"> Go to shopping cart</a> </div> <?php endif;?> <div class="adsense-snippet-all"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-8378091836388672" data-ad-slot="5101783172"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div class="col-md-12"> <br> <?php foreach($products as $product): ?> <div class="col-sm-6 col-md-4"> <div class="thumbnail" > <h4 class="text-center"><span class="label label-info">Category</span></h4> <img src="<?php print $product['image']?>" class="img-responsive"> <div class="caption"> <div class="row"> <div class="col-md-6 col-xs-6"> <h3><?php print $product['name']?></h3> </div> <div class="col-md-6 col-xs-6 price"> <h3> <label>$<?php print number_format($product['price']) ?></label> </h3> </div> </div> <p>32GB, 4GB Ram, 1080HD, 6.3 inches, WP 8</p> <div class="row"> <div class="col-md-6"> <a class="btn btn-primary btn-product"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a> </div> <div class="col-md-6"> <form method="post" action="shopping-cart.php?action=addcart"> <div class="col-md-4 text-center"> <button class="btn btn-success"><span class="glyphicon glyphicon-shopping-cart"></span> Buy</button> <input type="hidden" name="sku" value="<?php print $product['sku']?>"> </div> </form> </div> </div> <p> </p> </div> </div> </div> <?php endforeach;?> </div> </div> <script type="text/javascript" src="assets/js/app.js"></script>

🗑️ Step 5: Remove Products from the Cart

File PHP: cart.php
Next, our PHP code to remove products that were already added to the shopping cart session. You also have the option to empty the cart completely.

<?php error_reporting(0); //Setting session start session_start(); $total=0; $amount=0; //get action string $action = isset($_GET['action'])?$_GET['action']:""; //Empty All if($action=='emptyall') { $_SESSION['products'] =array(); header("Location:shopping-cart.php"); } //Empty one by one if($action=='empty') { $sku = $_GET['sku']; $products = $_SESSION['products']; unset($products[$sku]); $_SESSION['products']= $products; if (!empty($_SESSION['products'])) { header("Location:cart.php"); }else { header("Location:shopping-cart.php"); } } ?>

📋 Step 6: List Cart Items and Total

File PHP: cart.php
Given below our full HTML and PHP code, copy to use it. This markup lists the products stored in the PHP session, with their description, price, name and id, along with the running total.

<div class="container"> <div class="row"> <div class="col-sm-12 col-md-10 col-md-offset-1"> <table class="table table-hover"> <thead> <tr> <th>Product</th> <th>Quantity</th> <th class="text-center">Price</th> <th class="text-center">Total</th> <th> </th> </tr> </thead> <tbody> <?php $count = 1 ?> <?php foreach($_SESSION['products'] as $key=>$product):?> <tr> <td class="col-md-6"> <div class="media"> <a class="thumbnail pull-left" href="#"> <img class="media-object" src="<?php print $product['image']?>" style="width: 72px; height: 72px;"> </a> <div class="media-body"> <h4 class="media-heading"><a href="#"><?php print $product['name']?> </a></h4> <h5 class="media-heading"> by <a href="#">Brand name</a></h5> <span>Status: </span><span class="text-warning"><strong>Leaves warehouse in 2 - 3 weeks</strong></span> </div> </div></td> <td class="col-md-1" style="text-align: center"> <input disabled="" type="number" class="form-control" id="exampleInputEmail1" value="<?php print $product['qty'] ?>"> </td> <td class="col-md-1 text-center"><strong>$<?php print number_format($product['price']) ?></strong></td> <td class="col-md-1 text-center"><strong><?php print number_format($product['price']*$product['qty']) ?></strong></td> <td class="col-md-1"> <!-- cart.php?action=empty&sku=<?php print $key?> --> <a href="javascript:void(0)" data-id="<?php echo $key?>" data-title="Remove Item ?" type="button" class="btn btn-danger remove-item"> <span class="glyphicon glyphicon-remove"></span> Remove </a> <input type="hidden" id="remove-item" value="<?php echo $key?>"> </td> </tr> <?php $amount +=$product['price']*$product['qty']; ?> <?php $count++; ?> <?php endforeach; ?> <tr> <td> </td> <td> </td> <td> </td> <td><h5>Subtotal</h5></td> <td class="text-right"><h5><strong><?php print number_format($amount) ?></strong></h5></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td><h5>Estimated shipping</h5></td> <td class="text-right"><h5><strong><?php print number_format($amount) ?></strong></h5></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td><h3>Total</h3></td> <td class="text-right"><h3><strong><?php print number_format($amount) ?></strong></h3></td> </tr> <tr> <td> </td> <td> </td> <td> <a href="cart.php?action=emptyall"> <button type="button" class="btn btn-warning"> <span class="glyphicon glyphicon-shopping-cart"></span> Empty Cart </button> </a> </td> <td> <a href="shopping-cart.php"> <button type="button" class="btn btn-default"> <span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping </button> </a> </td> <td> <button type="button" class="btn btn-success"> Checkout <span class="glyphicon glyphicon-play"></span> </button></td> </tr> </tbody> </table> </div> </div> </div>

✅ Step 7: Confirm Before Removing an Item

File JAVASCRIPT: app.js
The remove() button asks for confirmation before removing an item from the cart.

$('a.remove-item').confirm({ title: 'Encountered an error!', content: 'Remove product from the basket.', type: 'red', buttons: { tryAgain: { text: 'yes, remove', btnClass: 'btn-red', action: function(){ value = this.$target.attr('data-id'); location.href ="cart.php?action=empty&sku=" + value; } }, close: function () { //event } } });

I hope you liked this simple shopping cart with PHP 5.6 and a MySQL database.