Inline Shopping Cart System In PHP with MySQL

Submitted by: 
Language: 
Visitors have accessed this post 5972 times.

A shopping cart is an imperative piece of each eCommerce venture. It causes the client to choose various things for 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 items 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 offer a powerful dev stack right out of the box.

Shopping Cart

Create Database Tables

Minium create 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,
  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,
  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;

DB Connection

Create the DBController.php file and paste following code.

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

Creating Template Files

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

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

Displaying Products

  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>

Add Delete Update Shopping Cart Functionality

I am going to create shopping cart just create the file name Shopping Cart.php and paste the following code. In this Class called Shopping Cart and different function 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.  
  123.  

Update cart quantity

  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. ?>

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.


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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.