Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Shopify Like Shopping Cart with Sticky Checkout using PHP

#1
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.&nbsp;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>.&nbsp; 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.&nbsp;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,&nbsp; 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.&nbsp;</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&nbsp;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.&nbsp;</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&nbsp;</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">&lt;?php namespace Phppot; use \Phppot\Cart; session_start(); require_once 'Model/Cart.php'; $cartModel = new Cart(); ?&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Shopify like sticky shopping cart in PHP&lt;/TITLE&gt; &lt;link href="./assets/css/phppot-style.css" type="text/css" rel="stylesheet" /&gt; &lt;script src="./vendor/jquery/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="./vendor/jquery/jquery-ui.js"&gt;&lt;/script&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;?php require_once './view/product-gallery.php'; ?&gt; &lt;div id="floating-cart-container"&gt; &lt;div id="cart-icon-container"&gt; &lt;img id="cart-icon" src="./view/images/cart-icon.png" alt="cartimg"&gt; &lt;div id="count"&gt; &lt;?php echo $cartModel-&gt;cartSessionItemCount; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="shopping-cart"&gt; &lt;div id="tbl-cart"&gt; &lt;div id="txt-heading"&gt; &lt;div id="cart-heading"&gt;Shopping Cart&lt;/div&gt; &lt;div id="close"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="cart-item"&gt; &lt;?php require_once './view/shopping-cart.php'; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="./assets/js/cart.js"&gt;&lt;/script&gt; &lt;/BODY&gt; &lt;/HTML&gt; </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">&lt;?php require_once __DIR__ . './../Model/Product.php'; $productModel = new Product(); ?&gt; &lt;div id="product-grid"&gt; &lt;div class="txt-heading"&gt;Products&lt;/div&gt; &lt;?php $productResult = $productModel-&gt;getAllProduct(); if (! empty($productResult)) { foreach ($productResult as $key =&gt; $value) { ?&gt; &lt;div class="product-item" data-name="&lt;?php echo $productResult[$key]["name"]; ?&gt;" data-price="&lt;?php echo "$" . $productResult[$key]["price"]; ?&gt;"&gt; &lt;div class="product-image"&gt; &lt;img src="&lt;?php echo $productResult[$key]["image"]; ?&gt;" id="&lt;?php echo $productResult[$key]["code"]; ?&gt;"&gt; &lt;/div&gt; &lt;div&gt; &lt;strong&gt;&lt;?php echo $productResult[$key]["name"]; ?&gt;&lt;/strong&gt; &lt;/div&gt; &lt;div class="product-price"&gt;&lt;?php echo "$" . $productResult[$key]["price"]; ?&gt;&lt;/div&gt; &lt;input type="button" id="add_&lt;?php echo $productResult[$key]["code"]; ?&gt;" value="Add to cart" class="btnAddAction" onClick="cartAction('add', '&lt;?php echo $productResult[$key]["code"]; ?&gt;')" /&gt; &lt;/div&gt; &lt;?php } } ?&gt; &lt;/div&gt; </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-&gt;addToCart(); break; </pre>
<h3>Model/Product.php</h3>
<pre class="prettyprint lang-php">&lt;?php use \Phppot\DataSource; class Product { private $ds; function __construct() { require_once __DIR__ . './../lib/DataSource.php'; $this-&gt;ds = new DataSource(); } function getAllProduct() { $query = "SELECT * FROM tblproduct ORDER BY id ASC"; $result = $this-&gt;ds-&gt;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">&lt;?php namespace Phppot; use \Phppot\Cart; require_once __DIR__ . './../Model/Cart.php'; $cartModel = new Cart(); ?&gt; &lt;input type="hidden" id="cart-item-count" value="&lt;?php echo $cartModel-&gt;cartSessionItemCount; ?&gt;"&gt; &lt;?php if ($cartModel-&gt;cartSessionItemCount &gt; 0) { ?&gt; &lt;table width="100%" id="cart-table" cellpadding="10" cellspacing="1" border="0"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Quantity&lt;/th&gt; &lt;th class="text-right"&gt;Price&lt;/th&gt; &lt;th class="text-right"&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;?php $item_total = 0; $i = 1; foreach ($_SESSION["cart_item"] as $item) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $item["name"]; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" name="quantity" class="quantity" value="&lt;?php echo $item['quantity']; ?&gt;" data-code='&lt;?php echo $item["code"]; ?&gt;' size=2 onChange="updatePrice(this)" /&gt; &lt;input type="hidden" class='total' name="total" value="&lt;?php echo $item["price"]; ?&gt;" /&gt;&lt;/td&gt; &lt;td align=right class="prc" id="price" &lt;?php echo $i;?&gt;&gt;&lt;?php echo $item["price"]; ?&gt;&lt;/td&gt; &lt;?php $i++; ?&gt; &lt;td class="text-right"&gt;&lt;a onClick="cartAction('remove','&lt;?php echo $item["code"]; ?&gt;')" class="btnRemoveAction"&gt;&lt;img src="./view/images/icon-delete.png" alt="Remove Item" /&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php $item_total += ($item["price"] * $item['quantity']); } ?&gt; &lt;tr id="tot"&gt; &lt;td colspan="3" align=right&gt;&lt;strong&gt;Total (USD): &lt;/strong&gt; &lt;span id="total"&gt;&lt;?php echo $item_total;?&gt;&lt;/span&gt;&lt;/td&gt; &lt;td align="right"&gt;&lt;a id="btnEmpty" onClick="cartAction('empty', '');"&gt;Empty Cart&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div id="checkout"&gt;Checkout&lt;/div&gt; &lt;?php } else { ?&gt; &lt;div id="empty-cart"&gt;Your cart is empty&lt;/div&gt; &lt;?php } ?&gt; </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 + '&amp;code=' + product_code + '&amp;quantity=' + $("#qty_" + product_code).val(); break; case "remove": queryString = 'action=' + action + '&amp;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&amp;code=' + code + '&amp;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">&lt;?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-&gt;addToCart(); break; case "edit": $totalPrice = $cartModel-&gt;editCart(); print $totalPrice; exit; break; case "remove": $cartModel-&gt;removeFromCart(); break; case "empty": $cartModel-&gt;emptyCart(); break; } } require_once '../view/shopping-cart.php'; ?&gt; </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">&lt;?php namespace Phppot; use \Phppot\DataSource; class Cart { private $ds; public $cartSessionItemCount = 0; function __construct() { require_once __DIR__ . './../lib/DataSource.php'; $this-&gt;ds = new DataSource(); if (! empty($_SESSION["cart_item"]) &amp;&amp; is_array($_SESSION["cart_item"])) { $this-&gt;cartSessionItemCount = count($_SESSION["cart_item"]); } } function addToCart() { $query = "SELECT * FROM tblproduct WHERE code = ?"; $paramType = "s"; $paramArray = array($_POST["code"]); $productByCode = $this-&gt;ds-&gt;select($query, $paramType, $paramArray); $itemArray = array( $productByCode[0]["code"] =&gt; array( 'name' =&gt; $productByCode[0]["name"], 'code' =&gt; $productByCode[0]["code"], 'quantity' =&gt; '1', 'price' =&gt; $productByCode[0]["price"] ) ); if (! empty($_SESSION["cart_item"])) { if (in_array($productByCode[0]["code"], $_SESSION["cart_item"])) { foreach ($_SESSION["cart_item"] as $k =&gt; $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"]) &amp;&amp; is_array($_SESSION["cart_item"])) { $this-&gt;cartSessionItemCount = count($_SESSION["cart_item"]); } } function editCart() { if (! empty($_SESSION["cart_item"])) { $total_price = 0; foreach ($_SESSION["cart_item"] as $k =&gt; $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"]) &amp;&amp; is_array($_SESSION["cart_item"])) { $this-&gt;cartSessionItemCount = count($_SESSION["cart_item"]); } } function removeFromCart() { if (! empty($_SESSION["cart_item"])) { foreach ($_SESSION["cart_item"] as $k =&gt; $v) { if ($_POST["code"] == $k) unset($_SESSION["cart_item"][$k]); if (empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } if (! empty($_SESSION["cart_item"]) &amp;&amp; is_array($_SESSION["cart_item"])) { $this-&gt;cartSessionItemCount = count($_SESSION["cart_item"]); } } function emptyCart() { unset($_SESSION["cart_item"]); $this-&gt;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/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016