• We just launched and are currently in beta. Join us as we build and grow the community.

Inline Shopping Cart System In PHP and MySQL Database Tutorial

vorbei

Gaming Prodigy
V Rep
0
0
0
Rep
0
V Vouches
0
0
0
Vouches
0
Posts
142
Likes
137
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
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.

phpmyadmin.png


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

    INTO

    `tbl_product`

    (

    `id`

    ,

    `name`

    ,

    `code`

    ,

    `image`

    ,

    `price`

    )

    VALUES
  9. (

    1

    ,

    '3D Camera'

    ,

    '3DcAM01'

    ,

    'product-images/camera.jpg'

    ,

    1500.00

    )

    ,
  10. (

    2

    ,

    'External Hard Drive'

    ,

    'USB02'

    ,

    'product-images/external-hard-drive.jpg'

    ,

    800.00

    )

    ,
  11. (

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

    DBController
  4. {

  5. private

    $host

    =

    "localhost"

    ;

  6. private

    $user

    =

    "root"

    ;

  7. private

    $password

    =

    ""

    ;

  8. private

    $database

    =

    "shopping_cart"

    ;

  9. private

    $conn

    ;

  10. function

    __construct(

    )
  11. {
  12. $this

    ->

    conn

    =

    mysqli_connect

    (

    $this

    ->

    host

    ,

    $this

    ->

    user

    ,

    $this

    ->

    password

    ,

    $this

    ->

    database

    )

    ;
  13. }

  14. public

    static function

    getConnection(

    )
  15. {
  16. if

    (

    empty

    (

    $this

    ->

    conn

    )

    )

    {
  17. new

    Database(

    )

    ;
  18. }
  19. }

  20. function

    getDBResult(

    $query

    ,

    $params

    =

    array

    (

    )

    )
  21. {

  22. $sql_statement

    =

    $this

    ->

    conn

    ->

    prepare

    (

    $query

    )

    ;
  23. if

    (

    !

    empty

    (

    $params

    )

    )

    {
  24. $this

    ->

    bindParams

    (

    $sql_statement

    ,

    $params

    )

    ;
  25. }
  26. $sql_statement

    ->

    execute

    (

    )

    ;
  27. $result

    =

    $sql_statement

    ->

    get_result

    (

    )

    ;

  28. if

    (

    $result

    ->

    num_rows

    >

    0

    )

    {
  29. while

    (

    $row

    =

    $result

    ->

    fetch_assoc

    (

    )

    )

    {
  30. $resultset

    [

    ]

    =

    $row

    ;
  31. }
  32. }

  33. if

    (

    !

    empty

    (

    $resultset

    )

    )

    {
  34. return

    $resultset

    ;
  35. }
  36. }

  37. function

    updateDB(

    $query

    ,

    $params

    =

    array

    (

    )

    )
  38. {
  39. $sql_statement

    =

    $this

    ->

    conn

    ->

    prepare

    (

    $query

    )

    ;
  40. if

    (

    !

    empty

    (

    $params

    )

    )

    {
  41. $this

    ->

    bindParams

    (

    $sql_statement

    ,

    $params

    )

    ;
  42. }
  43. $sql_statement

    ->

    execute

    (

    )

    ;
  44. }

  45. function

    bindParams(

    $sql_statement

    ,

    $params

    )
  46. {
  47. $param_type

    =

    ""

    ;
  48. foreach

    (

    $params

    as

    $query_param

    )

    {
  49. $param_type

    .=

    $query_param

    [

    "param_type"

    ]

    ;
  50. }

  51. $bind_params

    [

    ]

    =

    &

    $param_type

    ;
  52. foreach

    (

    $params

    as

    $k

    =>

    $query_param

    )

    {
  53. $bind_params

    [

    ]

    =

    &

    $params

    [

    $k

    ]

    [

    "param_value"

    ]

    ;
  54. }

  55. call_user_func_array

    (

    array

    (
  56. $sql_statement

    ,
  57. 'bind_param'
  58. )

    ,

    $bind_params

    )

    ;
  59. }
  60. }

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. $member_id

    =

    2

    ;

    // you can your integerate authentication module here to get logged in member

  5. $shoppingCart

    =

    new

    ShoppingCart(

    )

    ;
  6. if

    (

    !

    empty

    (

    $_GET

    [

    "action"

    ]

    )

    )

    {
  7. switch

    (

    $_GET

    [

    "action"

    ]

    )

    {
  8. case

    "add"

    :
  9. if

    (

    !

    empty

    (

    $_POST

    [

    "quantity"

    ]

    )

    )

    {

  10. $productResult

    =

    $shoppingCart

    ->

    getProductByCode

    (

    $_GET

    [

    "code"

    ]

    )

    ;

  11. $cartResult

    =

    $shoppingCart

    ->

    getCartItemByProduct

    (

    $productResult

    [

    0

    ]

    [

    "id"

    ]

    ,

    $member_id

    )

    ;

  12. if

    (

    !

    empty

    (

    $cartResult

    )

    )

    {
  13. // Update cart item quantity in database
  14. $newQuantity

    =

    $cartResult

    [

    0

    ]

    [

    "quantity"

    ]

    +

    $_POST

    [

    "quantity"

    ]

    ;
  15. $shoppingCart

    ->

    updateCartQuantity

    (

    $newQuantity

    ,

    $cartResult

    [

    0

    ]

    [

    "id"

    ]

    )

    ;
  16. }

    else

    {
  17. // Add to cart table
  18. $shoppingCart

    ->

    addToCart

    (

    $productResult

    [

    0

    ]

    [

    "id"

    ]

    ,

    $_POST

    [

    "quantity"

    ]

    ,

    $member_id

    )

    ;
  19. }
  20. }
  21. break

    ;
  22. case

    "remove"

    :
  23. // Delete single entry from the cart
  24. $shoppingCart

    ->

    deleteCartItem

    (

    $_GET

    [

    "id"

    ]

    )

    ;
  25. break

    ;
  26. case

    "empty"

    :
  27. // Empty cart
  28. $shoppingCart

    ->

    emptyCart

    (

    $member_id

    )

    ;
  29. break

    ;
  30. }
  31. }
  32. ?>
  33. <HTML>
  34. <HEAD>
  35. <TITLE>Shopping Cart in PHP</TITLE>
  36. <meta name="viewport" content="width=device-width, initial-scale=1">

  37. <link href="style.css" type="text/css" rel="stylesheet" />
  38. <script src="jquery-3.2.1.min.js"></script>
  39. <script>
  40. function increment_quantity(cart_id, price) {
  41. var inputQuantityElement = $("#input-quantity-"+cart_id);
  42. var newQuantity = parseInt($(inputQuantityElement).val())+1;
  43. var newPrice = newQuantity * price;
  44. save_to_db(cart_id, newQuantity, newPrice);
  45. }

  46. function decrement_quantity(cart_id, price) {
  47. var inputQuantityElement = $("#input-quantity-"+cart_id);
  48. if($(inputQuantityElement).val() > 1)
  49. {
  50. var newQuantity = parseInt($(inputQuantityElement).val()) - 1;
  51. var newPrice = newQuantity * price;
  52. save_to_db(cart_id, newQuantity, newPrice);
  53. }
  54. }

  55. function save_to_db(cart_id, new_quantity, newPrice) {
  56. var inputQuantityElement = $("#input-quantity-"+cart_id);
  57. var priceElement = $("#cart-price-"+cart_id);
  58. $.ajax({
  59. url : "update_cart_quantity.php",
  60. data : "cart_id="+cart_id+"&new_quantity="+new_quantity,
  61. type : 'post',
  62. success : function(response) {
  63. $(inputQuantityElement).val(new_quantity);
  64. $(priceElement).text("$"+newPrice);
  65. var totalQuantity = 0;
  66. $("input[id*='input-quantity-']").each(function() {
  67. var cart_quantity = $(this).val();
  68. totalQuantity = parseInt(totalQuantity) + parseInt(cart_quantity);
  69. });
  70. $("#total-quantity").text(totalQuantity);
  71. var totalItemPrice = 0;
  72. $("div[id*='cart-price-']").each(function() {
  73. var cart_price = $(this).text().replace("$","");
  74. totalItemPrice = parseInt(totalItemPrice) + parseInt(cart_price);
  75. });
  76. $("#total-price").text(totalItemPrice);
  77. }
  78. });
  79. }
  80. </script>

  81. </HEAD>
  82. <BODY>
  83. <?php
  84. $cartItem

    =

    $shoppingCart

    ->

    getMemberCartItem

    (

    $member_id

    )

    ;
  85. $item_quantity

    =

    0

    ;
  86. $item_price

    =

    0

    ;
  87. if

    (

    !

    empty

    (

    $cartItem

    )

    )

    {
  88. foreach

    (

    $cartItem

    as

    $item

    )

    {
  89. $item_quantity

    =

    $item_quantity

    +

    $item

    [

    "quantity"

    ]

    ;
  90. $item_price

    =

    $item_price

    +

    (

    $item

    [

    "price"

    ]

    *

    $item

    [

    "quantity"

    ]

    )

    ;
  91. }
  92. }
  93. ?>

  94. <div id="shopping-cart">
  95. <div class="txt-heading">
  96. <div class="txt-heading-label"><h1>Shopping Cart</h1></div>

  97. <a id="btnEmpty" href="index.php?action=empty"><img
  98. src="empty-cart.png" alt="empty-cart" title="Empty Cart"
  99. class="float-right" /></a>
  100. <div class="cart-status">
  101. <div>Total Quantity: <span id="total-quantity"><?php

    echo

    $item_quantity

    ;

    ?>

    </span></div>
  102. <div>Total Price: <span id="total-price"><?php

    echo

    $item_price

    ;

    ?>

    </span></div>
  103. </div>
  104. </div>

  105. <?php
  106. if

    (

    !

    empty

    (

    $cartItem

    )

    )

    {
  107. ?>
  108. <div class="shopping-cart-table">
  109. <div class="cart-item-container header">
  110. <div class="cart-info title">Title</div>
  111. <div class="cart-info">Quantity</div>
  112. <div class="cart-info price">Price</div>
  113. </div>

  114. <?php
  115. foreach

    (

    $cartItem

    as

    $item

    )

    {
  116. ?>
  117. <div class="cart-item-container">
  118. <div class="cart-info title">
  119. <?php

    echo

    $item

    [

    "name"

    ]

    ;

    ?>
  120. </div>

  121. <div class="cart-info quantity">
  122. <div class="btn-increment-decrement" onClick="decrement_quantity(<?php

    echo

    $item

    [

    "cart_id"

    ]

    ;

    ?>

    , '<?php

    echo

    $item

    [

    "price"

    ]

    ;

    ?>

    ')">-</div><input class="input-quantity"
  123. id="input-quantity-<?php

    echo

    $item

    [

    "cart_id"

    ]

    ;

    ?>

    " value="<?php

    echo

    $item

    [

    "quantity"

    ]

    ;

    ?>

    "><div class="btn-increment-decrement"
  124. onClick="increment_quantity(<?php

    echo

    $item

    [

    "cart_id"

    ]

    ;

    ?>

    , '<?php

    echo

    $item

    [

    "price"

    ]

    ;

    ?>

    ')">+</div>
  125. </div>

  126. <div class="cart-info price" id="cart-price-<?php

    echo

    $item

    [

    "cart_id"

    ]

    ;

    ?>

    ">
  127. <?php

    echo

    "$"

    .

    (

    $item

    [

    "price"

    ]

    *

    $item

    [

    "quantity"

    ]

    )

    ;

    ?>
  128. </div>


  129. <div class="cart-info action">
  130. <a
  131. href="index.php?action=remove&id=<?php

    echo

    $item

    [

    "cart_id"

    ]

    ;

    ?>

    "
  132. class="btnRemoveAction"><img
  133. src="icon-delete.png" alt="icon-delete"
  134. title="Remove Item" /></a>
  135. </div>
  136. </div>
  137. <?php
  138. }
  139. ?>
  140. </div>
  141. </div>
  142. <?php
  143. }
  144. ?>
  145. </div>
  146. <?php

    require_once

    "product-list.php"

    ;

    ?>

  147. </BODY>
  148. </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. </div>
  28. </form>
  29. </div>
  30. <?php
  31. }
  32. }
  33. ?>
  34. </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. class

    ShoppingCart extends

    DBController
  4. {

  5. function

    getAllProduct(

    )
  6. {
  7. $query

    =

    "SELECT * FROM tbl_product"

    ;

  8. $productResult

    =

    $this

    ->

    getDBResult

    (

    $query

    )

    ;
  9. return

    $productResult

    ;
  10. }

  11. function

    getMemberCartItem(

    $member_id

    )
  12. {
  13. $query

    =

    "SELECT tbl_product.*, tbl_cart.id as cart_id,tbl_cart.quantity FROM tbl_product, tbl_cart WHERE
  14. tbl_product.id = tbl_cart.product_id AND tbl_cart.member_id = ?"

    ;

  15. $params

    =

    array

    (
  16. array

    (
  17. "param_type"

    =>

    "i"

    ,
  18. "param_value"

    =>

    $member_id
  19. )
  20. )

    ;

  21. $cartResult

    =

    $this

    ->

    getDBResult

    (

    $query

    ,

    $params

    )

    ;
  22. return

    $cartResult

    ;
  23. }

  24. function

    getProductByCode(

    $product_code

    )
  25. {
  26. $query

    =

    "SELECT * FROM tbl_product WHERE code=?"

    ;

  27. $params

    =

    array

    (
  28. array

    (
  29. "param_type"

    =>

    "s"

    ,
  30. "param_value"

    =>

    $product_code
  31. )
  32. )

    ;

  33. $productResult

    =

    $this

    ->

    getDBResult

    (

    $query

    ,

    $params

    )

    ;
  34. return

    $productResult

    ;
  35. }

  36. function

    getCartItemByProduct(

    $product_id

    ,

    $member_id

    )
  37. {
  38. $query

    =

    "SELECT * FROM tbl_cart WHERE product_id = ? AND member_id = ?"

    ;

  39. $params

    =

    array

    (
  40. array

    (
  41. "param_type"

    =>

    "i"

    ,
  42. "param_value"

    =>

    $product_id
  43. )

    ,
  44. array

    (
  45. "param_type"

    =>

    "i"

    ,
  46. "param_value"

    =>

    $member_id
  47. )
  48. )

    ;

  49. $cartResult

    =

    $this

    ->

    getDBResult

    (

    $query

    ,

    $params

    )

    ;
  50. return

    $cartResult

    ;
  51. }

  52. function

    addToCart(

    $product_id

    ,

    $quantity

    ,

    $member_id

    )
  53. {
  54. $query

    =

    "INSERT INTO tbl_cart (product_id,quantity,member_id) VALUES (?, ?, ?)"

    ;

  55. $params

    =

    array

    (
  56. array

    (
  57. "param_type"

    =>

    "i"

    ,
  58. "param_value"

    =>

    $product_id
  59. )

    ,
  60. array

    (
  61. "param_type"

    =>

    "i"

    ,
  62. "param_value"

    =>

    $quantity
  63. )

    ,
  64. array

    (
  65. "param_type"

    =>

    "i"

    ,
  66. "param_value"

    =>

    $member_id
  67. )
  68. )

    ;

  69. $this

    ->

    updateDB

    (

    $query

    ,

    $params

    )

    ;
  70. }

  71. function

    updateCartQuantity(

    $quantity

    ,

    $cart_id

    )
  72. {
  73. $query

    =

    "UPDATE tbl_cart SET quantity = ? WHERE id= ?"

    ;

  74. $params

    =

    array

    (
  75. array

    (
  76. "param_type"

    =>

    "i"

    ,
  77. "param_value"

    =>

    $quantity
  78. )

    ,
  79. array

    (
  80. "param_type"

    =>

    "i"

    ,
  81. "param_value"

    =>

    $cart_id
  82. )
  83. )

    ;

  84. $this

    ->

    updateDB

    (

    $query

    ,

    $params

    )

    ;
  85. }

  86. function

    deleteCartItem(

    $cart_id

    )
  87. {
  88. $query

    =

    "DELETE FROM tbl_cart WHERE id = ?"

    ;

  89. $params

    =

    array

    (
  90. array

    (
  91. "param_type"

    =>

    "i"

    ,
  92. "param_value"

    =>

    $cart_id
  93. )
  94. )

    ;

  95. $this

    ->

    updateDB

    (

    $query

    ,

    $params

    )

    ;
  96. }

  97. function

    emptyCart(

    $member_id

    )
  98. {
  99. $query

    =

    "DELETE FROM tbl_cart WHERE member_id = ?"

    ;

  100. $params

    =

    array

    (
  101. array

    (
  102. "param_type"

    =>

    "i"

    ,
  103. "param_value"

    =>

    $member_id
  104. )
  105. )

    ;

  106. $this

    ->

    updateDB

    (

    $query

    ,

    $params

    )

    ;
  107. }
  108. }


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. $member_id

    =

    2

    ;

    // you can your integerate authentication module here to get logged in member

  4. $shoppingCart

    =

    new

    ShoppingCart(

    )

    ;

  5. $shoppingCart

    ->

    updateCartQuantity

    (

    $_POST

    [

    "new_quantity"

    ]

    ,

    $_POST

    [

    "cart_id"

    ]

    )

    ;

  6. ?>

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.


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,292

324,736

324,744

Top