Skip to main content

Inline Shopping Cart System In PHP and MySQL Database Tutorial

Language

A shopping cart is an imperative piece of each eCommerce venture. It causes the client to choose various things to buy and view add up to cost before presenting the request. On the off chance that you need to assemble a basic PHP shopping basket without any preparation, this well-ordered instructional exercise will help you a ton. In this instructional exercise, we'll give the entire guide and content to making a straightforward shopping cart in PHP.

This tutorial exercise is outlined in a way that can be actualized effectively in PHP venture and made straightforward the shopping cart idea. In our case content, we'll utilize PHP and jquery to store the items data in the truck. Once the request is put together by the client, the item data would be embedded into the database utilizing PHP and MySQL.

Prerequisites

For the purpose of this tutorial, I assume that you have PHP powered stack (a LAMP stack would do)on your web server.

To make sure that that I don’t get sidetracked by server-level issues, I decided to host my app on Cloudways PHP MySql hosting because it takes care of server and app setup and offers a powerful dev stack right out of the box.

Shopping Cart

Create Database Tables

First of all, create a new database naming shopping_cart. Minimum creates two tables like products and cart. Let’s paste the following MySQL code.

Cart Table

  1. CREATE TABLE `tbl_cart` (
  2. `id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `product_id` INT(11) NOT NULL,
  4. `quantity` INT(11) NOT NULL,
  5. `member_id` INT(11) NOT NULL
  6. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Products Table

  1. CREATE TABLE `tbl_product` (
  2. `id` INT(8) NOT NULL AUTO_INCREMENT,
  3. `name` VARCHAR(255) NOT NULL,
  4. `code` VARCHAR(255) NOT NULL,
  5. `image` text NOT NULL,
  6. `price` DOUBLE(10,2) NOT NULL
  7. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  8.  
  9. INSERT INTO `tbl_product` (`id`, `name`, `code`, `image`, `price`) VALUES
  10. (1, '3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
  11. (2, 'External Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
  12. (3, 'Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00);

DB Connection

Create the DBController.php file and paste following code.

  1. <?php
  2. <?php
  3.  
  4. class DBController
  5. {
  6.  
  7. private $host = "localhost";
  8.  
  9. private $user = "root";
  10.  
  11. private $password = "";
  12.  
  13. private $database = "shopping_cart";
  14.  
  15. private $conn;
  16.  
  17. function __construct()
  18. {
  19. $this->conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
  20. }
  21.  
  22. public static function getConnection()
  23. {
  24. if (empty($this->conn)) {
  25. new Database();
  26. }
  27. }
  28.  
  29. function getDBResult($query, $params = array())
  30. {
  31.  
  32. $sql_statement = $this->conn->prepare($query);
  33. if (! empty($params)) {
  34. $this->bindParams($sql_statement, $params);
  35. }
  36. $sql_statement->execute();
  37. $result = $sql_statement->get_result();
  38.  
  39. if ($result->num_rows > 0) {
  40. while ($row = $result->fetch_assoc()) {
  41. $resultset[] = $row;
  42. }
  43. }
  44.  
  45. if (! empty($resultset)) {
  46. return $resultset;
  47. }
  48. }
  49.  
  50. function updateDB($query, $params = array())
  51. {
  52. $sql_statement = $this->conn->prepare($query);
  53. if (! empty($params)) {
  54. $this->bindParams($sql_statement, $params);
  55. }
  56. $sql_statement->execute();
  57. }
  58.  
  59. function bindParams($sql_statement, $params)
  60. {
  61. $param_type = "";
  62. foreach ($params as $query_param) {
  63. $param_type .= $query_param["param_type"];
  64. }
  65.  
  66. $bind_params[] = & $param_type;
  67. foreach ($params as $k => $query_param) {
  68. $bind_params[] = & $params[$k]["param_value"];
  69. }
  70.  
  71. $sql_statement,
  72. 'bind_param'
  73. ), $bind_params);
  74. }
  75. }

Creating Template Files

I’m going to creating template files . Let’s create index.php file and paste the following code.

  1. <?php
  2. <?php
  3. require_once "ShoppingCart.php";
  4.  
  5. $member_id = 2; // you can your integerate authentication module here to get logged in member
  6.  
  7. $shoppingCart = new ShoppingCart();
  8. if (! empty($_GET["action"])) {
  9. switch ($_GET["action"]) {
  10. case "add":
  11. if (! empty($_POST["quantity"])) {
  12.  
  13. $productResult = $shoppingCart->getProductByCode($_GET["code"]);
  14.  
  15. $cartResult = $shoppingCart->getCartItemByProduct($productResult[0]["id"], $member_id);
  16.  
  17. if (! empty($cartResult)) {
  18. // Update cart item quantity in database
  19. $newQuantity = $cartResult[0]["quantity"] + $_POST["quantity"];
  20. $shoppingCart->updateCartQuantity($newQuantity, $cartResult[0]["id"]);
  21. } else {
  22. // Add to cart table
  23. $shoppingCart->addToCart($productResult[0]["id"], $_POST["quantity"], $member_id);
  24. }
  25. }
  26. break;
  27. case "remove":
  28. // Delete single entry from the cart
  29. $shoppingCart->deleteCartItem($_GET["id"]);
  30. break;
  31. case "empty":
  32. // Empty cart
  33. $shoppingCart->emptyCart($member_id);
  34. break;
  35. }
  36. }
  37. ?>
  38. <HTML>
  39. <HEAD>
  40. <TITLE>Shopping Cart in PHP</TITLE>
  41. <meta name="viewport" content="width=device-width, initial-scale=1">
  42.  
  43. <link href="style.css" type="text/css" rel="stylesheet" />
  44. <script src="jquery-3.2.1.min.js"></script>
  45. <script>
  46. function increment_quantity(cart_id, price) {
  47. var inputQuantityElement = $("#input-quantity-"+cart_id);
  48. var newQuantity = parseInt($(inputQuantityElement).val())+1;
  49. var newPrice = newQuantity * price;
  50. save_to_db(cart_id, newQuantity, newPrice);
  51. }
  52.  
  53. function decrement_quantity(cart_id, price) {
  54. var inputQuantityElement = $("#input-quantity-"+cart_id);
  55. if($(inputQuantityElement).val() > 1)
  56. {
  57. var newQuantity = parseInt($(inputQuantityElement).val()) - 1;
  58. var newPrice = newQuantity * price;
  59. save_to_db(cart_id, newQuantity, newPrice);
  60. }
  61. }
  62.  
  63. function save_to_db(cart_id, new_quantity, newPrice) {
  64. var inputQuantityElement = $("#input-quantity-"+cart_id);
  65. var priceElement = $("#cart-price-"+cart_id);
  66. $.ajax({
  67. url : "update_cart_quantity.php",
  68. data : "cart_id="+cart_id+"&new_quantity="+new_quantity,
  69. type : 'post',
  70. success : function(response) {
  71. $(inputQuantityElement).val(new_quantity);
  72. $(priceElement).text("$"+newPrice);
  73. var totalQuantity = 0;
  74. $("input[id*='input-quantity-']").each(function() {
  75. var cart_quantity = $(this).val();
  76. totalQuantity = parseInt(totalQuantity) + parseInt(cart_quantity);
  77. });
  78. $("#total-quantity").text(totalQuantity);
  79. var totalItemPrice = 0;
  80. $("div[id*='cart-price-']").each(function() {
  81. var cart_price = $(this).text().replace("$","");
  82. totalItemPrice = parseInt(totalItemPrice) + parseInt(cart_price);
  83. });
  84. $("#total-price").text(totalItemPrice);
  85. }
  86. });
  87. }
  88. </script>
  89.  
  90. </HEAD>
  91. <BODY>
  92. <?php
  93. $cartItem = $shoppingCart->getMemberCartItem($member_id);
  94. $item_quantity = 0;
  95. $item_price = 0;
  96. if (! empty($cartItem)) {
  97. foreach ($cartItem as $item) {
  98. $item_quantity = $item_quantity + $item["quantity"];
  99. $item_price = $item_price + ($item["price"] * $item["quantity"]);
  100. }
  101. }
  102. ?>
  103.  
  104. <div id="shopping-cart">
  105. <div class="txt-heading">
  106. <div class="txt-heading-label"><h1>Shopping Cart</h1></div>
  107.  
  108. <a id="btnEmpty" href="index.php?action=empty"><img
  109. src="empty-cart.png" alt="empty-cart" title="Empty Cart"
  110. class="float-right" /></a>
  111. <div class="cart-status">
  112. <div>Total Quantity: <span id="total-quantity"><?php echo $item_quantity; ?></span></div>
  113. <div>Total Price: <span id="total-price"><?php echo $item_price; ?></span></div>
  114. </div>
  115. </div>
  116.  
  117. <?php
  118. if (! empty($cartItem)) {
  119. ?>
  120. <div class="shopping-cart-table">
  121. <div class="cart-item-container header">
  122. <div class="cart-info title">Title</div>
  123. <div class="cart-info">Quantity</div>
  124. <div class="cart-info price">Price</div>
  125. </div>
  126.  
  127. <?php
  128. foreach ($cartItem as $item) {
  129. ?>
  130. <div class="cart-item-container">
  131. <div class="cart-info title">
  132. <?php echo $item["name"]; ?>
  133. </div>
  134.  
  135. <div class="cart-info quantity">
  136. <div class="btn-increment-decrement" onClick="decrement_quantity(<?php echo $item["cart_id"]; ?>, '<?php echo $item["price"]; ?>')">-</div><input class="input-quantity"
  137. id="input-quantity-<?php echo $item["cart_id"]; ?>" value="<?php echo $item["quantity"]; ?>"><div class="btn-increment-decrement"
  138. onClick="increment_quantity(<?php echo $item["cart_id"]; ?>, '<?php echo $item["price"]; ?>')">+</div>
  139. </div>
  140.  
  141. <div class="cart-info price" id="cart-price-<?php echo $item["cart_id"]; ?>">
  142. <?php echo "$". ($item["price"] * $item["quantity"]); ?>
  143. </div>
  144.  
  145.  
  146. <div class="cart-info action">
  147. <a
  148. href="index.php?action=remove&id=<?php echo $item["cart_id"]; ?>"
  149. class="btnRemoveAction"><img
  150. src="icon-delete.png" alt="icon-delete"
  151. title="Remove Item" /></a>
  152. </div>
  153. </div>
  154. <?php
  155. }
  156. ?>
  157. </div>
  158. </div>
  159. <?php
  160. }
  161. ?>
  162. </div>
  163. <?php require_once "product-list.php"; ?>
  164.  
  165. </BODY>
  166. </HTML>

Displaying Products

The below code is template to display that product list. Save the below code as product-list.php.

  1. <div id="product-grid">
  2. <div class="txt-heading">
  3. <div class="txt-heading-label">Products</div>
  4. </div>
  5. <?php
  6. $query = "SELECT * FROM tbl_product";
  7. $product_array = $shoppingCart->getAllProduct($query);
  8. if (! empty($product_array)) {
  9. foreach ($product_array as $key => $value) {
  10. ?>
  11. <div class="product-item">
  12. <form method="post"
  13. action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
  14. <div class="product-image">
  15. <img src="<?php echo $product_array[$key]["image"]; ?>">
  16. <div class="product-title">
  17. <?php echo $product_array[$key]["name"]; ?>
  18. </div>
  19. </div>
  20. <div class="product-footer">
  21. <div class="float-right">
  22. <input type="text" name="quantity" value="1"
  23. size="2" class="input-cart-quantity" /><input type="image"
  24. src="add-to-cart.png" class="btnAddAction" />
  25. </div>
  26. <div class="product-price float-left" id="product-price-<?php echo $product_array[$key]["code"]; ?>"><?php echo "$".$product_array[$key]["price"]; ?></div>
  27.  
  28. </div>
  29. </form>
  30. </div>
  31. <?php
  32. }
  33. }
  34. ?>
  35. </div>

Shopping Cart Class

I am going to create a shopping cart just create the file name ShoppingCart.php and paste the following code. This Class called Shopping Cart and different functions like add, delete, update.

  1. <?php
  2. require_once "DBController.php";
  3.  
  4. class ShoppingCart extends DBController
  5. {
  6.  
  7. function getAllProduct()
  8. {
  9. $query = "SELECT * FROM tbl_product";
  10.  
  11. $productResult = $this->getDBResult($query);
  12. return $productResult;
  13. }
  14.  
  15. function getMemberCartItem($member_id)
  16. {
  17. $query = "SELECT tbl_product.*, tbl_cart.id as cart_id,tbl_cart.quantity FROM tbl_product, tbl_cart WHERE
  18. tbl_product.id = tbl_cart.product_id AND tbl_cart.member_id = ?";
  19.  
  20. $params = array(
  21. "param_type" => "i",
  22. "param_value" => $member_id
  23. )
  24. );
  25.  
  26. $cartResult = $this->getDBResult($query, $params);
  27. return $cartResult;
  28. }
  29.  
  30. function getProductByCode($product_code)
  31. {
  32. $query = "SELECT * FROM tbl_product WHERE code=?";
  33.  
  34. $params = array(
  35. "param_type" => "s",
  36. "param_value" => $product_code
  37. )
  38. );
  39.  
  40. $productResult = $this->getDBResult($query, $params);
  41. return $productResult;
  42. }
  43.  
  44. function getCartItemByProduct($product_id, $member_id)
  45. {
  46. $query = "SELECT * FROM tbl_cart WHERE product_id = ? AND member_id = ?";
  47.  
  48. $params = array(
  49. "param_type" => "i",
  50. "param_value" => $product_id
  51. ),
  52. "param_type" => "i",
  53. "param_value" => $member_id
  54. )
  55. );
  56.  
  57. $cartResult = $this->getDBResult($query, $params);
  58. return $cartResult;
  59. }
  60.  
  61. function addToCart($product_id, $quantity, $member_id)
  62. {
  63. $query = "INSERT INTO tbl_cart (product_id,quantity,member_id) VALUES (?, ?, ?)";
  64.  
  65. $params = array(
  66. "param_type" => "i",
  67. "param_value" => $product_id
  68. ),
  69. "param_type" => "i",
  70. "param_value" => $quantity
  71. ),
  72. "param_type" => "i",
  73. "param_value" => $member_id
  74. )
  75. );
  76.  
  77. $this->updateDB($query, $params);
  78. }
  79.  
  80. function updateCartQuantity($quantity, $cart_id)
  81. {
  82. $query = "UPDATE tbl_cart SET quantity = ? WHERE id= ?";
  83.  
  84. $params = array(
  85. "param_type" => "i",
  86. "param_value" => $quantity
  87. ),
  88. "param_type" => "i",
  89. "param_value" => $cart_id
  90. )
  91. );
  92.  
  93. $this->updateDB($query, $params);
  94. }
  95.  
  96. function deleteCartItem($cart_id)
  97. {
  98. $query = "DELETE FROM tbl_cart WHERE id = ?";
  99.  
  100. $params = array(
  101. "param_type" => "i",
  102. "param_value" => $cart_id
  103. )
  104. );
  105.  
  106. $this->updateDB($query, $params);
  107. }
  108.  
  109. function emptyCart($member_id)
  110. {
  111. $query = "DELETE FROM tbl_cart WHERE member_id = ?";
  112.  
  113. $params = array(
  114. "param_type" => "i",
  115. "param_value" => $member_id
  116. )
  117. );
  118.  
  119. $this->updateDB($query, $params);
  120. }
  121. }
  122.  

Update cart quantity

The code below is the PHP script that serves as the update operation of each product's quantity in the cart when adding or decreasing button is triggered. Save the file as update_cart_quantity.php.

  1. <?php
  2. require_once "ShoppingCart.php";
  3.  
  4. $member_id = 2; // you can your integerate authentication module here to get logged in member
  5.  
  6. $shoppingCart = new ShoppingCart();
  7.  
  8. $shoppingCart->updateCartQuantity($_POST["new_quantity"], $_POST["cart_id"]);
  9.  
  10. ?>

Demo

Conclusion

We trust this guide will enable you to comprehend the essential shopping to truck usefulness in PHP with session and MySQL. Utilizing this procedure and content you'll have the capacity to execute a shopping basket in your web application in a flash. Additionally, you can update it with cutting-edge usefulness in view of your shopping basket prerequisite.

That's the end of this tutorial and I hope this will help you with what you are looking for. The working source sample that I have created for this tutorial is included, kindly click the "download" button below to download the source code zip file.

Enjoy :)

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.

Add new comment