Wednesday, 3 August 2016

Simple PHP Mysql Shopping Cart







If you want to looking for a making of simple PHP MySQL shopping cart tutorial? Here is the good news for you, here have learn a step by step making of shopping cart and easy to follow this tutorial. In this post we are going to learn how to make a simple PHP shopping cart application. This PHP shopping cart script is purposely kept as simple as possible for beginner php programmer. Here I have to describe how to displaying product list from MySql database. In each displaying product we have given options for entering item quantity and add that item to shopping cart and that shopping cart items will be stored into a session variable and if you want to remove item from shopping cart then you can clear session variable and can removing items from the shopping cart. I have used very simple core php code for creating this simple shopping cart by using get and post methods of php.









Source Code


    
--  
 -- Table structure for table `tbl_product`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_product` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(255) NOT NULL,  
  `image` varchar(255) NOT NULL,  
  `price` double(10,2) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;  
 --  
 -- Dumping data for table `tbl_product`  
 --  
 INSERT INTO `tbl_product` (`id`, `name`, `image`, `price`) VALUES  
 (1, 'Samsung J2 Pro', '1.jpg', 100.00),  
 (2, 'HP Notebook', '2.jpg', 299.00),  
 (3, 'Panasonic T44 Lite', '3.jpg', 125.00);
   

index.php


    <?php   
 session_start();  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 if(isset($_POST["add_to_cart"]))  
 {  
      if(isset($_SESSION["shopping_cart"]))  
      {  
           $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
           if(!in_array($_GET["id"], $item_array_id))  
           {  
                $count = count($_SESSION["shopping_cart"]);  
                $item_array = array(  
                     'item_id'               =>     $_GET["id"],  
                     'item_name'               =>     $_POST["hidden_name"],  
                     'item_price'          =>     $_POST["hidden_price"],  
                     'item_quantity'          =>     $_POST["quantity"]  
                );  
                $_SESSION["shopping_cart"][$count] = $item_array;  
           }  
           else  
           {  
                echo '<script>alert("Item Already Added")</script>';  
                echo '<script>window.location="index.php"</script>';  
           }  
      }  
      else  
      {  
           $item_array = array(  
                'item_id'               =>     $_GET["id"],  
                'item_name'               =>     $_POST["hidden_name"],  
                'item_price'          =>     $_POST["hidden_price"],  
                'item_quantity'          =>     $_POST["quantity"]  
           );  
           $_SESSION["shopping_cart"][0] = $item_array;  
      }  
 }  
 if(isset($_GET["action"]))  
 {  
      if($_GET["action"] == "delete")  
      {  
           foreach($_SESSION["shopping_cart"] as $keys => $values)  
           {  
                if($values["item_id"] == $_GET["id"])  
                {  
                     unset($_SESSION["shopping_cart"][$keys]);  
                     echo '<script>alert("Item Removed")</script>';  
                     echo '<script>window.location="index.php"</script>';  
                }  
           }  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Simple PHP Mysql Shopping Cart</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Simple PHP Mysql Shopping Cart</h3><br />  
                <?php  
                $query = "SELECT * FROM tbl_product ORDER BY id ASC";  
                $result = mysqli_query($connect, $query);  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                ?>  
                <div class="col-md-4">  
                     <form method="post" action="index.php?action=add&id=<?php echo $row["id"]; ?>">  
                          <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">  
                               <img src="<?php echo $row["image"]; ?>" class="img-responsive" /><br />  
                               <h4 class="text-info"><?php echo $row["name"]; ?></h4>  
                               <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>  
                               <input type="text" name="quantity" class="form-control" value="1" />  
                               <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />  
                               <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />  
                               <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />  
                          </div>  
                     </form>  
                </div>  
                <?php  
                     }  
                }  
                ?>  
                <div style="clear:both"></div>  
                <br />  
                <h3>Order Details</h3>  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="40%">Item Name</th>  
                               <th width="10%">Quantity</th>  
                               <th width="20%">Price</th>  
                               <th width="15%">Total</th>  
                               <th width="5%">Action</th>  
                          </tr>  
                          <?php   
                          if(!empty($_SESSION["shopping_cart"]))  
                          {  
                               $total = 0;  
                               foreach($_SESSION["shopping_cart"] as $keys => $values)  
                               {  
                          ?>  
                          <tr>  
                               <td><?php echo $values["item_name"]; ?></td>  
                               <td><?php echo $values["item_quantity"]; ?></td>  
                               <td>$ <?php echo $values["item_price"]; ?></td>  
                               <td>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>  
                               <td><a href="index.php?action=delete&id=<?php echo $values["item_id"]; ?>"><span class="text-danger">Remove</span></a></td>  
                          </tr>  
                          <?php  
                                    $total = $total + ($values["item_quantity"] * $values["item_price"]);  
                               }  
                          ?>  
                          <tr>  
                               <td colspan="3" align="right">Total</td>  
                               <td align="right">$ <?php echo number_format($total, 2); ?></td>  
                               <td></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>
   

80 comments:

  1. Tanks... This is a grate tutorial.

    ReplyDelete
  2. an errors appears

    Fatal error: Call to undefined function array_column() in C:\xampp\htdocs\PhpTelesindo\mapping\form.php on line 8

    ReplyDelete
    Replies
    1. can you help us, Webslesson !?

      Delete
    2. Hey you have to update your php version (in order to use array_column() you have to have php5 + ) thanks

      Delete
    3. In order to use array_column() you have to have php version 5 and above .in order to see what version you use in windows use ()
      and then update the version

      Delete
    4. You are using older version of php install latest version

      Delete
  3. how you insert the image in data base plss explain it

    ReplyDelete
    Replies
    1. IDK if you still need help, but just click on your table -> sql, and then put this text INSERT INTO 'table'(column_name) VALUE('desired_value');

      If you want to put multiple, do this: INSERT INTO 'table'(column_name1, column_name2,...) VALUES('desired_value1', 'desired_value2',...);

      Delete
    2. Fatal error: Call to undefined function array_column() in C:\xampp\htdocs\apa\index.php on line 8

      Delete
  4. I have a question, This works as responsive design? also it's a very good tutorial!!

    ReplyDelete
  5. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp2\htdocs\cart.php on line 68

    could you tell us how to solve the problem!

    thanks

    ReplyDelete
  6. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\Simple\index.php on line 68


    who can help

    ReplyDelete
  7. Hey thankyou for the source code , please tell me how do i checkout after the items are added to the cart... please help me

    ReplyDelete
  8. ITS NOT WORK AFTER REMOVE PRODUCT ........PLZ CORRECT THIS PROBLEM AND UPDATE

    ReplyDelete
  9. hi i want to add quantite when the product is already exist how to replace this code : "
    echo 'alert("Item Already Added")';
    echo 'window.location="index.php"'; "

    ReplyDelete
  10. I have a problem it only add one item to cart , if you try to add another item it just replaces the first one.

    can anyone help.

    ReplyDelete
  11. It just add one item to cart if you try to add another one it will just replace the first one.

    ReplyDelete
  12. Greetings This is a wonderful tutorials. I wish to carry this a step forward by adding the cart items into the ordered database via a check out button. Could you please Help me to advance these Codes. Thank You!

    ReplyDelete
  13. Please reply me what is the best way to add a product into cart using database or session

    ReplyDelete
  14. How to update product quantity

    ReplyDelete
  15. why images are unseen on server?

    ReplyDelete
  16. i found problem while adding the three products and removing the second one. it loops on adding the product on the same array :(

    ReplyDelete
  17. i found problem while adding the three products and removing the second one. it loops on adding the product on the same array :(

    ReplyDelete
  18. Fatal error: Call to undefined function array_column() in E:\wamp\www\easy-cart\index.php on line 8

    ReplyDelete
  19. Could any one can tell me why it happens?

    ReplyDelete
  20. how to image show from database??

    ReplyDelete
  21. Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\1\newtest.php:1) in C:\xampp\htdocs\1\newtest.php on line 96

    Notice: Undefined index: shopping_cart in C:\xampp\htdocs\1\newtest.php on line 135

    Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\1\newtest.php on line 135

    ReplyDelete
  22. Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\1\newtest.php:1) in C:\xampp\htdocs\1\newtest.php on line 96

    Notice: Undefined index: shopping_cart in C:\xampp\htdocs\1\newtest.php on line 135

    Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\1\newtest.php on line 135

    ReplyDelete
  23. I have used the code and everything is working just fine but my product list is long. So when I add a product to cart the page reloads and takes to top of page. Can you tell me how can I stop the page scroll to top on adding and deleting a product.

    ReplyDelete
  24. OMG!!!!! THANK YOU SO MUCH!! IT HELPED A LOT!! SML FROM THE PHILIPPINES <3 HOPING FOR MORE TUTORIALS. KEEP ON HELPING NEWBIES LIKE ME. :) YOUR THE TRUE HERO. XOXO

    ReplyDelete
  25. How can I insert this data in shopping cart into database from array?

    ReplyDelete
  26. How can I get those arrays from shopping cart and insert it into database

    ReplyDelete
  27. How to insert the shopping cart to database?

    ReplyDelete
  28. error: after remove item, we added items replace exist items.
    who place order? who get data from table to database

    ReplyDelete
  29. need help i cant click any of my add to cart bittons

    ReplyDelete
  30. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cart\index.php:1) in C:\xampp\htdocs\cart\index.php on line 2



    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\cart\index.php on line 65


    plc help to solve

    ReplyDelete
  31. thank you but if i will add one item on my cart means i should be reduce one item in db know can u upload that kind of code please

    ReplyDelete
  32. Fatal error: Call to undefined function array_column() in C:\wamp\www\Simple-PHP-Shopping-Cart-master\index.php on line 8

    ReplyDelete
  33. need update code also.. i have tried but not working for me..

    ReplyDelete
  34. need update code also.. i have tried but not working for me..

    ReplyDelete
  35. thanx very much, simple and beautiful

    ReplyDelete
  36. thanx very mch
    simple and beautiful

    ReplyDelete
  37. now how do we save the order in a mysql database table say "orders"
    then create something like daily orders for the previous 5 days

    ReplyDelete
  38. can you post a code for updating quantity

    ReplyDelete
  39. can anyone write a update quantity in shopping cart on this code

    ReplyDelete
  40. When I do this:
    -add 1st product
    -add 2nd product
    -add 3rd product
    -remove 2nd product
    -add 2nd product

    My order looks like this:
    1st product
    2nd product

    Instead of:
    1st product
    3rd product
    2nd product

    Why is that happening? Why is the 2nd product replacing 3rd instead of being added onto the order list?

    ReplyDelete
  41. that is too much vulnerable anyone can edit in price in html code in browser

    ReplyDelete
  42. how do i proceed with the checkout button? i want to put this inside the database.

    "
    $id = $product['id'];
    $name = $product['name'];
    $quantity = $product['quantity'];
    $price = $product['price'];
    $sql = "INSERT INTO order(product_id,product_name,product_price,quantity)
    VALUES ('$id','$name','$quantity','$price')";
    mysqli_query($db,$sql);}


    "

    ReplyDelete
  43. Can you post addto cart by checkbox?this function is much useful

    ReplyDelete
  44. it takes only one time id ,second time id does not get by cart,it shows fatal error

    ReplyDelete
  45. How to display all the order back in summary?

    ReplyDelete
  46. What is Shopping_cart in sessions bracket ?

    ReplyDelete
  47. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp2\htdocs\cart.php on line 68

    could you tell us how to solve the problem!

    ReplyDelete
  48. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp2\htdocs\cart.php on line 68

    could you tell us how to solve the problem!

    ReplyDelete
  49. Could you please help me, I want to display my whole user information in web. Basically user enter Ticket detail, and he could purchase 2,3 tickets. After adding tickets information. I want to print whole ticket detail dynamically with suitable method. Kindly guide me with this problem

    ReplyDelete
  50. i was getting same error , and when i checked i found that my database and table name was different so u can change it if you have putted it different.

    ReplyDelete
  51. Just a heads up,this script has no security measures in place to prevent various attacks.DO NOT PUBLISH YOUR SITE ONLINE USING THIS SOURCE CODE!

    ReplyDelete
  52. como adicionar ao carrinho?

    obrigado

    ReplyDelete
  53. After creating a simple cart system using php. How can we send that data via email?

    ReplyDelete
  54. How to dend the data of cart via email

    ReplyDelete
  55. how to update product quantity in shopping cart

    ReplyDelete
  56. Thanks for the great explanation but I've faced two problems
    I've got error inn database :
    #1396 - Operation CREATE USER failed for 'tbl_product'@'localhost'

    also in php :
    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\add to cart\index.php on line 68

    ReplyDelete
  57. when i click on remove it didn't remove any product

    ReplyDelete
  58. Muito bom este trabalho! Me desculpe pelo atrevimento de lhe pedir para que você nos dê a honra de vê-lo deixando nota 1000 seu trabalho, por adicionar um módulo de pagamento para que a loja receba do cliente. Parabéns!

    ReplyDelete
  59. Here is the super extra 20x fast server and cheap best and cheapest web hosting service to grow your big and small business on all search engine & get more sales or traffic, 70% blast discount, 24 hour live chat support.

    ReplyDelete