06-03-2020, 11:36 PM
Shopify Like Shopping Cart with Sticky Checkout using PHP
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/shopify-like-shopping-cart-with-sticky-checkout-using-php.png" width="550" height="461" title="" alt="" /></div><div><p>Last modified on December 3rd, 2019 by Vincy.</p>
<p>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.</p>
<p>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.</p>
<p><img class="alignnone size-large wp-image-10617" src="https://phppot.com/wp-content/uploads/2019/09/Shopify-Like-Shopping-Cart-with-Sticky-Checkout-using-PHP-550x461.png" alt="Shopify Like Shopping Cart with Sticky Checkout using PHP" width="550" height="461" srcset="https://phppot.com/wp-content/uploads/2019/09/Shopify-Like-Shopping-Cart-with-Sticky-Checkout-using-PHP-550x461.png 550w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...ng-PHP.png 940w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>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.</p>
<p>In this article, we are going to see how to create a featured sticky <a href="https://phppot.com/php/simple-php-shopping-cart/">shopping cart script in PHP</a>. In Shopify like the eCommerce platform, it gives sticky shopping cart checkout as a feature.</p>
<p>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.</p>
<p>This article will guide you with simple steps to create a shopping cart in PHP. If you are planning to create a <a href="https://phppot.com/php/enriched-responsive-shopping-cart-in-php/">shopping cart with a modern outlook</a> and features, it will help you to achieve this.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#advantages-of-sticky-shopping-cart">Advantages of sticky shopping cart</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#php-sticky-shopping-cart-software-development-overview">PHP sticky shopping cart example overview</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#file-structure">File structure</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#landing-page-with-product-gallery-and-shopping-cart-components">Landing page with product gallery and shopping cart components</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#render-product-tiles-in-a-gallery">Render product tiles in a gallery</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#display-cart-items-from-php-session">Display cart items from PHP Session</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#manage-cart-actions-editdeleteempty">Manage Cart actions edit, delete, empty</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#product-database-table-sql-script">Product database table SQL script</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#php-shopify-like-sticky-shopping-cart-output">PHP Shopify like sticky shopping cart example output</a></li>
</ol>
<p>eCommerce software with sticky shopping cart checkout has many advantages,</p>
<ul>
<li>It gives an enriched modern feel to the application.</li>
<li>It helps users to see the cart status at any moment.</li>
<li>It encourages users to checkout and thus increasing the conversion.</li>
</ul>
<p>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.</p>
<p>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. </p>
<p>The functionalities supported by this example are here with the corresponding description.</p>
<p><strong>Fetching product data from the database:<br /></strong>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.</p>
<p><strong>Create product gallery with add-to-cart option:<br /></strong>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.</p>
<p><strong>Manage the cart with PHP session:<br /></strong>I have used the PHP session array to store and manage the cart items.</p>
<p><strong>Handling the add, edit, delete and empty cart:<br /></strong>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.</p>
<h2 id="file-structure">File structure</h2>
<p>The below screenshot shows the file structure of this example. </p>
<p><img class="alignnone size-large wp-image-10567" src="https://phppot.com/wp-content/uploads/2019/09/shopify-like-sticky-shopping-cart-in-php-550x785.jpg" alt="Shopify-Like Sticky Shopping Cart in PHP" width="550" height="785" srcset="https://phppot.com/wp-content/uploads/2019/09/shopify-like-sticky-shopping-cart-in-php-550x785.jpg 550w, https://phppot.com/wp-content/uploads/20...10x300.jpg 210w, https://phppot.com/wp-content/uploads/20...in-php.jpg 694w" sizes="(max-width: 550px) 100vw, 550px"></p>
<ul>
<li><strong>view/product-gallery.php</strong> – It includes a PHP loop to iterate the products to form the gallery.</li>
<li><strong>view/shopping-cart.php</strong> – It contains a HTML table to display the cart item from the PHP session.</li>
<li><strong>css/style.css</strong> – It has the styles to <a href="https://phppot.com/php/amazon-like-product-images-showcase-for-shopping-cart/">showcase product gallery</a>. It helps in shopping cart software design containing appropriate cart action controls.</li>
<li><strong>cart.js</strong> – This JavaScript file contains action handlers to process requests via AJAX. It also contains code to fix the shopping cart panel in a fixed position while scrolling.</li>
<li><strong>handle-cart-ep.php </strong>– This is the PHP endpoint invoked from AJAX code to add, edit, remove cart items.</li>
<li><strong>tblproduct.sql</strong> – This SQL contains product database CREATE and INSERT statements.</li>
<li><strong>DataSource.php</strong> – This is a generic file we used for our examples requires a database.</li>
<li><strong>data</strong> – This directory is the product image source used while creating the gallery.</li>
</ul>
<h2 id="landing-page-with-product-gallery-and-shopping-cart-components">A landing page with product gallery and shopping cart components</h2>
<p>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.</p>
<p>By clicking this icon, a script will toggle the shopping cart window.</p>
<p>This HTML includes cart.js JavaScript file. It contains all the jQuery AJAX code needed for performing cart actions and UI update.</p>
<pre class="prettyprint"><?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> </pre>
<h2 id="render-product-tiles-in-a-gallery">Render product tiles in a gallery</h2>
<p>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.</p>
<p>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.</p>
<p>The gallery tile shows products name, price and a preview image in a card-like view. Also, it contains an add-to-cart button.</p>
<p>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.</p>
<p>Below code shows the <a href="https://phppot.com/php/responsive-product-gallery-for-shopping-cart/">HTML used to show a gallery view</a> for this shopping cart software example.</p>
<pre class="prettyprint lang-php"><?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> </pre>
<h3>Add-to-Cart from Product Gallery</h3>
<p>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.</p>
<p>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.</p>
<p>In this example, the switch case handles cart actions. It request and process add, <a href="https://phppot.com/php/ajax-cart-edit-in-php-shopping-cart/">edit (item quantity)</a>, remove (single cart item) and empty cart.</p>
<p>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.</p>
<pre class="prettyprint">case "add": $cartModel->addToCart(); break; </pre>
<h3>Model/Product.php</h3>
<pre class="prettyprint lang-php"><?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; } } </pre>
<h2 id="display-cart-items-from-php-session">Display shopping cart items from PHP Session</h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<pre class="prettyprint lang-php"><?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 } ?> </pre>
<h2 id="manage-cart-actions-editdeleteempty">Handle shopping cart actions edit, remove, empty on checkout page</h2>
<p>In each row of the showing cart tabular window, it displays editable quantity with an input box. Users can <a href="https://phppot.com/php/shopping-cart-item-quantity-increment-decrement-with-ajax/">increment or decrement the cart item quantity</a> of a particular item.</p>
<p>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.</p>
<p>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.</p>
<p>Also, the shopping cart window has the option to empty the cart with one single click.</p>
<p>The below code shows the switch cases created to trigger and perform cart actions.</p>
<h3>cart.js</h3>
<pre class="prettyprint">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"); }); </pre>
<h3>ajax/handle-cart-ep.php</h3>
<pre class="prettyprint"><?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'; ?> </pre>
<h3>Model/Cart.php</h3>
<p>This is the model class used to create, edit and clear cart sessions.</p>
<pre class="prettyprint lang-php"><?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; } } </pre>
<h2 id="product-database-table-sql-script">Product database table SQL script</h2>
<p>The following SQL script has the CREATE and the INSERT query. It will help to put the product table in your development environment.</p>
<pre class="prettyprint">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); </pre>
<p><img class="alignnone size-large wp-image-10562" src="https://phppot.com/wp-content/uploads/2019/09/shopify-like-floating-shopping-cart-output-550x291.jpg" alt="Shopify-Like Floating Shopping Cart Output" width="550" height="291" srcset="https://phppot.com/wp-content/uploads/2019/09/shopify-like-floating-shopping-cart-output-550x291.jpg 550w, https://phppot.com/wp-content/uploads/20...00x159.jpg 300w, https://phppot.com/wp-content/uploads/20...68x407.jpg 768w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p><a class="download" href="https://phppot.com/downloads/shopify-like-sticky-shopping-cart-in-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2019/09/...using-php/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/shopify-like-shopping-cart-with-sticky-checkout-using-php.png" width="550" height="461" title="" alt="" /></div><div><p>Last modified on December 3rd, 2019 by Vincy.</p>
<p>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.</p>
<p>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.</p>
<p><img class="alignnone size-large wp-image-10617" src="https://phppot.com/wp-content/uploads/2019/09/Shopify-Like-Shopping-Cart-with-Sticky-Checkout-using-PHP-550x461.png" alt="Shopify Like Shopping Cart with Sticky Checkout using PHP" width="550" height="461" srcset="https://phppot.com/wp-content/uploads/2019/09/Shopify-Like-Shopping-Cart-with-Sticky-Checkout-using-PHP-550x461.png 550w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...ng-PHP.png 940w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>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.</p>
<p>In this article, we are going to see how to create a featured sticky <a href="https://phppot.com/php/simple-php-shopping-cart/">shopping cart script in PHP</a>. In Shopify like the eCommerce platform, it gives sticky shopping cart checkout as a feature.</p>
<p>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.</p>
<p>This article will guide you with simple steps to create a shopping cart in PHP. If you are planning to create a <a href="https://phppot.com/php/enriched-responsive-shopping-cart-in-php/">shopping cart with a modern outlook</a> and features, it will help you to achieve this.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#advantages-of-sticky-shopping-cart">Advantages of sticky shopping cart</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#php-sticky-shopping-cart-software-development-overview">PHP sticky shopping cart example overview</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#file-structure">File structure</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#landing-page-with-product-gallery-and-shopping-cart-components">Landing page with product gallery and shopping cart components</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#render-product-tiles-in-a-gallery">Render product tiles in a gallery</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#display-cart-items-from-php-session">Display cart items from PHP Session</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#manage-cart-actions-editdeleteempty">Manage Cart actions edit, delete, empty</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#product-database-table-sql-script">Product database table SQL script</a></li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#php-shopify-like-sticky-shopping-cart-output">PHP Shopify like sticky shopping cart example output</a></li>
</ol>
<p>eCommerce software with sticky shopping cart checkout has many advantages,</p>
<ul>
<li>It gives an enriched modern feel to the application.</li>
<li>It helps users to see the cart status at any moment.</li>
<li>It encourages users to checkout and thus increasing the conversion.</li>
</ul>
<p>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.</p>
<p>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. </p>
<p>The functionalities supported by this example are here with the corresponding description.</p>
<p><strong>Fetching product data from the database:<br /></strong>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.</p>
<p><strong>Create product gallery with add-to-cart option:<br /></strong>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.</p>
<p><strong>Manage the cart with PHP session:<br /></strong>I have used the PHP session array to store and manage the cart items.</p>
<p><strong>Handling the add, edit, delete and empty cart:<br /></strong>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.</p>
<h2 id="file-structure">File structure</h2>
<p>The below screenshot shows the file structure of this example. </p>
<p><img class="alignnone size-large wp-image-10567" src="https://phppot.com/wp-content/uploads/2019/09/shopify-like-sticky-shopping-cart-in-php-550x785.jpg" alt="Shopify-Like Sticky Shopping Cart in PHP" width="550" height="785" srcset="https://phppot.com/wp-content/uploads/2019/09/shopify-like-sticky-shopping-cart-in-php-550x785.jpg 550w, https://phppot.com/wp-content/uploads/20...10x300.jpg 210w, https://phppot.com/wp-content/uploads/20...in-php.jpg 694w" sizes="(max-width: 550px) 100vw, 550px"></p>
<ul>
<li><strong>view/product-gallery.php</strong> – It includes a PHP loop to iterate the products to form the gallery.</li>
<li><strong>view/shopping-cart.php</strong> – It contains a HTML table to display the cart item from the PHP session.</li>
<li><strong>css/style.css</strong> – It has the styles to <a href="https://phppot.com/php/amazon-like-product-images-showcase-for-shopping-cart/">showcase product gallery</a>. It helps in shopping cart software design containing appropriate cart action controls.</li>
<li><strong>cart.js</strong> – This JavaScript file contains action handlers to process requests via AJAX. It also contains code to fix the shopping cart panel in a fixed position while scrolling.</li>
<li><strong>handle-cart-ep.php </strong>– This is the PHP endpoint invoked from AJAX code to add, edit, remove cart items.</li>
<li><strong>tblproduct.sql</strong> – This SQL contains product database CREATE and INSERT statements.</li>
<li><strong>DataSource.php</strong> – This is a generic file we used for our examples requires a database.</li>
<li><strong>data</strong> – This directory is the product image source used while creating the gallery.</li>
</ul>
<h2 id="landing-page-with-product-gallery-and-shopping-cart-components">A landing page with product gallery and shopping cart components</h2>
<p>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.</p>
<p>By clicking this icon, a script will toggle the shopping cart window.</p>
<p>This HTML includes cart.js JavaScript file. It contains all the jQuery AJAX code needed for performing cart actions and UI update.</p>
<pre class="prettyprint"><?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> </pre>
<h2 id="render-product-tiles-in-a-gallery">Render product tiles in a gallery</h2>
<p>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.</p>
<p>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.</p>
<p>The gallery tile shows products name, price and a preview image in a card-like view. Also, it contains an add-to-cart button.</p>
<p>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.</p>
<p>Below code shows the <a href="https://phppot.com/php/responsive-product-gallery-for-shopping-cart/">HTML used to show a gallery view</a> for this shopping cart software example.</p>
<pre class="prettyprint lang-php"><?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> </pre>
<h3>Add-to-Cart from Product Gallery</h3>
<p>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.</p>
<p>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.</p>
<p>In this example, the switch case handles cart actions. It request and process add, <a href="https://phppot.com/php/ajax-cart-edit-in-php-shopping-cart/">edit (item quantity)</a>, remove (single cart item) and empty cart.</p>
<p>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.</p>
<pre class="prettyprint">case "add": $cartModel->addToCart(); break; </pre>
<h3>Model/Product.php</h3>
<pre class="prettyprint lang-php"><?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; } } </pre>
<h2 id="display-cart-items-from-php-session">Display shopping cart items from PHP Session</h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<pre class="prettyprint lang-php"><?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 } ?> </pre>
<h2 id="manage-cart-actions-editdeleteempty">Handle shopping cart actions edit, remove, empty on checkout page</h2>
<p>In each row of the showing cart tabular window, it displays editable quantity with an input box. Users can <a href="https://phppot.com/php/shopping-cart-item-quantity-increment-decrement-with-ajax/">increment or decrement the cart item quantity</a> of a particular item.</p>
<p>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.</p>
<p>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.</p>
<p>Also, the shopping cart window has the option to empty the cart with one single click.</p>
<p>The below code shows the switch cases created to trigger and perform cart actions.</p>
<h3>cart.js</h3>
<pre class="prettyprint">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"); }); </pre>
<h3>ajax/handle-cart-ep.php</h3>
<pre class="prettyprint"><?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'; ?> </pre>
<h3>Model/Cart.php</h3>
<p>This is the model class used to create, edit and clear cart sessions.</p>
<pre class="prettyprint lang-php"><?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; } } </pre>
<h2 id="product-database-table-sql-script">Product database table SQL script</h2>
<p>The following SQL script has the CREATE and the INSERT query. It will help to put the product table in your development environment.</p>
<pre class="prettyprint">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); </pre>
<p><img class="alignnone size-large wp-image-10562" src="https://phppot.com/wp-content/uploads/2019/09/shopify-like-floating-shopping-cart-output-550x291.jpg" alt="Shopify-Like Floating Shopping Cart Output" width="550" height="291" srcset="https://phppot.com/wp-content/uploads/2019/09/shopify-like-floating-shopping-cart-output-550x291.jpg 550w, https://phppot.com/wp-content/uploads/20...00x159.jpg 300w, https://phppot.com/wp-content/uploads/20...68x407.jpg 768w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p><a class="download" href="https://phppot.com/downloads/shopify-like-sticky-shopping-cart-in-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2019/09/...using-php/