Do you know online consumers in the US spent $517 billion last year? Which is a 15% increase from the previous year? eCommerce is an old domain, but still, it disrupts the tech world.
These days, the live shopping cart software have a remarkable business scope. They are increasing in the number day by day. There is a significant market today to sell products in an online store.
PHP is the main technology that runs the majority of the shopping cart software on the Internet. Developing a full-fledged PHP shopping cart software is not as easy as it looks.
In this article, we are going to see how to create a featured sticky shopping cart script in PHP. In Shopify like the eCommerce platform, it gives sticky shopping cart checkout as a feature.
I used jQuery and CSS to make the shopping cart unit sticky on a fixed position on page scroll. So, it will make the cart unit be always near to access and encourage the users to checkout.
This article will guide you with simple steps to create a shopping cart in PHP. If you are planning to create a shopping cart with a modern outlook and features, it will help you to achieve this.
eCommerce software with sticky shopping cart checkout has many advantages,
This Shopify-like sticky shopping cart software in PHP uses database and PHP sessions. It manages products in the database and shopping cart items in the PHP session.
It has a product gallery, cart HTML table and supports cart actions like add, edit and delete. These action handlers use AJAX to invoke code added with server endpoints.
The functionalities supported by this example are here with the corresponding description.
Fetching product data from the database:
A PHP MySQL code section accesses product database to read the data like product name, code, price, and preview images. If data found then this will result in an array of products.
Create product gallery with add-to-cart option:
Create a product gallery with an add-to-cart option. A PHP loop iterates product array to form the gallery view. Each product in the gallery has an add-to-cart button.
Manage the cart with PHP session:
I have used the PHP session array to store and manage the cart items.
Handling the add, edit, delete and empty cart:
This example code supports users to add a new product into the cart. A HTML table will display the cart item with edit quantity, remove an entry and more options.
The below screenshot shows the file structure of this example.
This HTML code includes the PHP source to render product gallery, shopping cart software pagee. It also shows a sticky cart icon with the current cart items count.
By clicking this icon, a script will toggle the shopping cart window.
This HTML includes cart.js JavaScript file. It contains all the jQuery AJAX code needed for performing cart actions and UI update.
<?php
namespace Phppot;
use \Phppot\Cart;
session_start();
require_once 'Model/Cart.php';
$cartModel = new Cart();
?>
<HTML>
<HEAD>
<TITLE>Shopify like sticky shopping cart in PHP</TITLE>
<link href="./assets/css/phppot-style.css" type="text/css"
rel="stylesheet" />
<script src="./vendor/jquery/jquery.min.js" type="text/javascript"></script>
<script src="./vendor/jquery/jquery-ui.js"></script>
</HEAD>
<BODY>
<?php require_once './view/product-gallery.php'; ?>
<div id="floating-cart-container">
<div id="cart-icon-container">
<img id="cart-icon" src="./view/images/cart-icon.png"
alt="cartimg">
<div id="count">
<?php echo $cartModel->cartSessionItemCount; ?>
</div>
</div>
<div id="shopping-cart">
<div id="tbl-cart">
<div id="txt-heading">
<div id="cart-heading">Shopping Cart</div>
<div id="close"></div>
</div>
<div id="cart-item">
<?php require_once './view/shopping-cart.php'; ?>
</div>
</div>
</div>
</div>
<script src="./assets/js/cart.js"></script>
</BODY>
</HTML>
The product gallery is a HTML container embedded with PHP-MySQL script. The PHP code prepares MySQL select statement to get the product result in an array.
By iterating this array result with a PHP foreach statement, it reads the database row data. With this product data, it forms the gallery tile on each loop iteration.
The gallery tile shows products name, price and a preview image in a card-like view. Also, it contains an add-to-cart button.
This’s button’s click event invokes AJAX to add the particular product to the cart session. Each product has a unique code which is the reference to create and manage each cart session index.
Below code shows the HTML used to show a gallery view for this shopping cart software example.
<?php
require_once __DIR__ . './../Model/Product.php';
$productModel = new Product();
?>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$productResult = $productModel->getAllProduct();
if (! empty($productResult)) {
foreach ($productResult as $key => $value) {
?>
<div class="product-item"
data-name="<?php echo $productResult[$key]["name"]; ?>"
data-price="<?php echo "$" . $productResult[$key]["price"]; ?>">
<div class="product-image">
<img src="<?php echo $productResult[$key]["image"]; ?>"
id="<?php echo $productResult[$key]["code"]; ?>">
</div>
<div>
<strong><?php echo $productResult[$key]["name"]; ?></strong>
</div>
<div class="product-price"><?php echo "$" . $productResult[$key]["price"]; ?></div>
<input type="button"
id="add_<?php echo $productResult[$key]["code"]; ?>"
value="Add to cart" class="btnAddAction"
onClick="cartAction('add', '<?php echo $productResult[$key]["code"]; ?>')" />
</div>
<?php
}
}
?>
</div>
The add-to-cart button in each product tile is the trigger to add a cart item into the PHP session. When the user clicks on the ‘Add to Cart’ button, it calls the cartAction() function to execute the add action via AJAX.
In this function call, it has the product id as an argument. In PHP the code fetches the product code, price to add to the cart session.
In this example, the switch case handles cart actions. It request and process add, edit (item quantity), remove (single cart item) and empty cart.
In the “add” case I checked if the current cart item already exists in the cart session. If so, I will update its quantity, otherwise, I will push the entire item array into the session index. The product code is the session index of each cart item to keep the uniqueness. The addToCart function has the code to add the cart item into the PHP session.
case "add":
$cartModel->addToCart();
break;
<?php
use \Phppot\DataSource;
class Product {
private $ds;
function __construct() {
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
function getAllProduct()
{
$query = "SELECT * FROM tblproduct ORDER BY id ASC";
$result = $this->ds->select($query);
return $result;
}
}
This code shows the HTML table containing the list of cart items added by the user. The cart data is dynamic from the PHP session.
In shopping-cart.php file, it iterates the $_SESSION[“cart”] array and displays the cart row. Each row has data like product title, price, quantity. It also has the option to edit the item quantity and to delete a single item from the cart.
This cart window is sticky that lets the users access the cart and see the status at any time. Also, it shows the total item price by summing up the individual cart items.
<?php
namespace Phppot;
use \Phppot\Cart;
require_once __DIR__ . './../Model/Cart.php';
$cartModel = new Cart();
?>
<input type="hidden" id="cart-item-count" value="<?php echo $cartModel->cartSessionItemCount; ?>">
<?php
if ($cartModel->cartSessionItemCount > 0) {
?>
<table width="100%" id="cart-table" cellpadding="10" cellspacing="1" border="0">
<tbody>
<tr>
<th>Name</th>
<th>Quantity</th>
<th class="text-right">Price</th>
<th class="text-right">Action</th>
</tr>
<?php
$item_total = 0;
$i = 1;
foreach ($_SESSION["cart_item"] as $item) {
?>
<tr>
<td><?php echo $item["name"]; ?></td>
<td><input type="number" name="quantity"
class="quantity"
value="<?php echo $item['quantity']; ?>" data-code='<?php echo $item["code"]; ?>' size=2 onChange="updatePrice(this)" /> <input
type="hidden" class='total' name="total"
value="<?php echo $item["price"]; ?>" /></td>
<td align=right class="prc" id="price" <?php echo $i;?>><?php echo $item["price"]; ?></td>
<?php $i++; ?>
<td class="text-right"><a
onClick="cartAction('remove','<?php echo $item["code"]; ?>')"
class="btnRemoveAction"><img
src="./view/images/icon-delete.png"
alt="Remove Item" /></a></td>
</tr>
<?php
$item_total += ($item["price"] * $item['quantity']);
}
?>
<tr id="tot">
<td colspan="3" align=right><strong>Total (USD): </strong> <span id="total"><?php echo $item_total;?></span></td>
<td align="right"><a id="btnEmpty" onClick="cartAction('empty', '');">Empty
Cart</a></td>
</tr>
</tbody>
</table>
<div id="checkout">Checkout</div>
<?php
} else {
?>
<div id="empty-cart">Your cart is empty</div>
<?php
}
?>
In each row of the showing cart tabular window, it displays editable quantity with an input box. Users can increment or decrement the cart item quantity of a particular item.
On changing the quantity, and AJAX code will send the data to get the calculated price based on the new quantity. Then, it will update the price in the row.
There is a remove option for each cart item. By clicking the remove action, an ajax call will request PHP code to perform the remove action. It will pass the product code as an argument to clear the particular cart session index.
Also, the shopping cart window has the option to empty the cart with one single click.
The below code shows the switch cases created to trigger and perform cart actions.
function cartAction(action, product_code) {
var queryString = "";
if (action != "") {
switch (action) {
case "add":
queryString = 'action=' + action + '&code=' + product_code + '&quantity=' + $("#qty_" + product_code).val();
break;
case "remove":
queryString = 'action=' + action + '&code=' + product_code;
break;
case "empty":
queryString = 'action=' + action;
break;
}
}
jQuery.ajax({
url: "ajax/handle-cart-ep.php",
data: queryString,
type: "POST",
success: function (data) {
$("#cart-item").html(data);
$("#count").text($("#cart-item-count").val());
},
error: function () {}
});
}
function updatePrice(obj){
var quantity = $(obj).val();
var code = $(obj).data('code');
queryString = 'action=edit&code=' + code + '&quantity=' + quantity;
$.ajax({
type: 'post',
url: "ajax/handle-cart-ep.php",
data: queryString,
success: function(data) {
$("#total").text(data);
}
});
}
$(document).ready(function () {
$("#cart-icon-container").click(function () {
$("#shopping-cart").toggle();
});
var top = parseInt($("#shopping-cart").height())/2;
$("#shopping-cart").css("margin-top", "-" + top + "px");
});
<?php
namespace Phppot;
use \Phppot\Cart;
require_once __DIR__ . './../Model/Cart.php';
$cartModel = new Cart();
session_start();
if (! empty($_POST["action"])) {
switch ($_POST["action"]) {
case "add":
$cartModel->addToCart();
break;
case "edit":
$totalPrice = $cartModel->editCart();
print $totalPrice;
exit;
break;
case "remove":
$cartModel->removeFromCart();
break;
case "empty":
$cartModel->emptyCart();
break;
}
}
require_once '../view/shopping-cart.php';
?>
This is the model class used to create, edit and clear cart sessions.
<?php
namespace Phppot;
use \Phppot\DataSource;
class Cart {
private $ds;
public $cartSessionItemCount = 0;
function __construct() {
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) {
$this->cartSessionItemCount = count($_SESSION["cart_item"]);
}
}
function addToCart() {
$query = "SELECT * FROM tblproduct WHERE code = ?";
$paramType = "s";
$paramArray = array($_POST["code"]);
$productByCode = $this->ds->select($query, $paramType, $paramArray);
$itemArray = array(
$productByCode[0]["code"] => array(
'name' => $productByCode[0]["name"],
'code' => $productByCode[0]["code"],
'quantity' => '1',
'price' => $productByCode[0]["price"]
)
);
if (! empty($_SESSION["cart_item"])) {
if (in_array($productByCode[0]["code"], $_SESSION["cart_item"])) {
foreach ($_SESSION["cart_item"] as $k => $v) {
if ($productByCode[0]["code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) {
$this->cartSessionItemCount = count($_SESSION["cart_item"]);
}
}
function editCart() {
if (! empty($_SESSION["cart_item"])) {
$total_price = 0;
foreach ($_SESSION["cart_item"] as $k => $v) {
if ($_POST["code"] == $k) {
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
$total_price = $total_price + ($_SESSION["cart_item"][$k]["quantity"] * $_SESSION["cart_item"][$k]["price"] );
}
return $total_price;
}
if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) {
$this->cartSessionItemCount = count($_SESSION["cart_item"]);
}
}
function removeFromCart() {
if (! empty($_SESSION["cart_item"])) {
foreach ($_SESSION["cart_item"] as $k => $v) {
if ($_POST["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if (empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
if (! empty($_SESSION["cart_item"]) && is_array($_SESSION["cart_item"])) {
$this->cartSessionItemCount = count($_SESSION["cart_item"]);
}
}
function emptyCart() {
unset($_SESSION["cart_item"]);
$this->cartSessionItemCount = 0;
}
}
The following SQL script has the CREATE and the INSERT query. It will help to put the product table in your development environment.
CREATE TABLE IF NOT EXISTS `tblproduct` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `tblproduct`
--
INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'FinePix Pro2 3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'Luxury Ultra thin Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00),
(3, 'XP 1155 Intel Core Laptop', 'LPN45', 'product-images/laptop.jpg', 800.00),
(4, 'Water Bottle', 'wristWear02', 'product-images/external-hard-drive.jpg', 600.00);
Html language is very important for web developer.
Yeah that’s true Kumar :-)
very very useful site ever waoooooo!
Thank you Moshy.
anyone available for coding
Hi Mick,
Get in touch with me via my email and let’s take it forward.
Wow! Thank you so much. You are a genius… It’s working perfectly
Hey Sadeeq, thank you :-)
hey u are just awesome ,thanks a lot ..can i contact you..i am new in this field.so plz
Thank you, sure Ashok.
Hi your email contact form is not working.
Hi Craig,
Thank you for the information. I will check it out immediately. Thanks a lot.
Thank you so much for sharing all this. These are super useful.
Welcome Manshi.