Creating cart (Shopping Cart) simple with PHP

View: 1125    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: References   Fields: Other

9 point/3 review File has been tested

Creating applications or Shopping Cart shopping cart is always the most important part for web workers. With stormy growth of electronic commerce, the increasing number of website sales with all genres appear.

Introduction

Creating applications or Shopping Cart shopping cart is always the most important part for web workers. With stormy growth of electronic commerce, the increasing number of website sales with all genres appear. In fact, when building a sales website, you do not need to do much programming, because there are so many open source support building an online store such as Magento, CS Cart, Presstashop ... .. But do What they do, if you can build yourself a shopping cart separately, then both can improve programming, while they can better understand the mechanism by which a sales website needs.

Today, in this article, I will be with you every step creates a simple shopping cart with PHP. And through this article, you can develop more advanced for a basket as the main standard for your website.

First, you need to create the following four files to Cart (shopping cart) their:

Config.php (database connectivity)
Index.php (page displays a list of products from a database)
Cart_update.php (updated basket)
View_cart.php (see the review cart before payment)
Okie, that's it, and now we will proceed step by step.

Step 1: Create a database

First of all, we need a data store of product information such as product name, product image ... sql following paragraph:

01
02
03
04
05
06
07
08
09
10
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_code` varchar(60) NOT NULL,
  `product_name` varchar(60) NOT NULL,
  `product_desc` tinytext NOT NULL,
  `product_img_name` varchar(60) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_code` (`product_code`)
) AUTO_INCREMENT=1 ;

If you do not know how to use SQL statements to create, they can go to phpMyAdmin to create sql structure above. When creating the table (table) is done, you can add a list of products as shown in the following table:

product-details-mysql

Step 2: connecting database

Once we have the data stored product information, we will proceed with a data connection to display the screen. The config.php file that you open and copy the following code inside it:

1
2
3
4
5
6
7
8
<?php
$currency = '$'; // đơn vị tiền tệ
$db_username = 'root'; // user name
$db_password = '';// password
$db_name = 'demo'; // tên cơ sở dữ liệu
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
?>

You remember the value changes according to the notes that his next record offline.

Step 3: Display product information and shopping cart

Now is the time that we will show a list of products for sale,. Because we will use to store temporary information session cart, so the first thing to do is we have to activate the session. Open the index.php file and copy the following code to paste into it:

1
2
3
4
<?php
session_start();
include_once("config.php");
?>

Index.php page will display two content, content 1 will list the product (in the middle) and the 2nd content displayed Cart (located right next door).

Product Listing

You copy this code and paste it in to the index.php file to display the product from the database:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<div class="products">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    
    $results = $mysqli->query("SELECT * FROM products ORDER BY id ASC");
    if ($results) {
        //output results from database
        while($obj = $results->fetch_object())
        {
            
            echo '<div class="product">';
            echo '<form method="post" action="cart_update.php">';
            echo '<div class="product-thumb"><img src="images/'.$obj->product_img_name.'"></div>';
            echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
            echo '<div class="product-desc">'.$obj->product_desc.'</div>';
            echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
            echo '</div>';
            echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
            echo '<input type="hidden" name="type" value="add" />';
            echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
            echo '</form>';
            echo '</div>';
        }
    
}
?>
</div>

The Shopping Cart:

Then copy and paste the following code to the index.php file to display cart:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
    $total = 0;
    echo '<ol>';
    foreach ($_SESSION["products"] as $cart_itm)
    {
        echo '<li class="cart-itm">';
        echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
        echo '<h3>'.$cart_itm["name"].'</h3>';
        echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
        echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
        echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
        echo '</li>';
        $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
        $total = ($total + $subtotal);
    }
    echo '</ol>';
    echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> <a href="view_cart.php">Check-out!</a></span>';
    echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&return_url='.$current_url.'">Empty Cart</a></span>';
}else{
    echo 'Your Cart is empty';
}
?>
</div>

Step 4: Update cart

Carts will be added and deleted function product is being put into the basket. When you click on "Add to Cart", the form will send a hidden value is the product code (product code) with the number (quantity) to Cart_update.php file through POST method. We will use the information sent to it to retrieve information from the database product. You copy the code below and paste it into Cart_update.php file. Each command has to notes, you can see the notes to understand the code better.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
session_start(); //start session
include_once("config.php"); //include config file
 
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
    $return_url = base64_decode($_GET["return_url"]); //return url
    session_destroy();
    header('Location:'.$return_url);
}
 
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty    = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url     = base64_decode($_POST["return_url"]); //return url
    
    //limit quantity for single product
    if($product_qty > 10){
        die('<div align="center">This demo does not allowed more than 10 quantity!<br /><a href="http://sanwebe.com/assets/paypal-shopping-cart-integration/">Back To Products</a>.</div>');
    }
 
    //MySqli query - get details of item from db using product code
    $results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
    $obj = $results->fetch_object();
    
    if ($results) { //we have the product info
        
        //prepare array for the session variable
        $new_product = array(array('name'=>$obj->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));
        
        if(isset($_SESSION["products"])) //if we have the session
        {
            $found = false; //set found item to false
            
            foreach ($_SESSION["products"] as $cart_itm) //loop through session array
            {
                if($cart_itm["code"] == $product_code){ //the item exist in array
 
                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, 'price'=>$cart_itm["price"]);
                    $found = true;
                }else{
                    //item doesn't exist in the list, just retrive old info and prepare array for session var
                    $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
                }
            }
            
            if($found == false) //we didn't find item in array
            {
                //add new user item in array
                $_SESSION["products"] = array_merge($product, $new_product);
            }else{
                //found user item in array list, and increased the quantity
                $_SESSION["products"] = $product;
            }
            
        }else{
            //create a new session var if does not exist
            $_SESSION["products"] = $new_product;
        }
        
    }
    
    //redirect back to original page
    header('Location:'.$return_url);
}
 
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
    $product_code   = $_GET["removep"]; //get the product code to remove
    $return_url     = base64_decode($_GET["return_url"]); //get return url
 
    
    foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
    {
        if($cart_itm["code"]!=$product_code){ //item does,t exist in the list
            $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
        }
        
        //create a new product list for cart
        $_SESSION["products"] = $product;
    }
    
    //redirect back to original page
    header('Location:'.$return_url);
}

Step 5: Get an overview Carts

Now we will list all the products in the cart, the quantity, the price, and the total amount to be paid before the "bid". If you want to raise, in this section you can add tax and shipping ... You copy the following code to fileView_cart.php.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
session_start();
include_once("config.php");
    if(isset($_SESSION["products"]))
    {
        $total = 0;
        echo '<form method="post" action="PAYMENT-GATEWAY">';
        echo '<ul>';
        $cart_items = 0;
        foreach ($_SESSION["products"] as $cart_itm)
        {
           $product_code = $cart_itm["code"];
           $results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
           $obj = $results->fetch_object();
            
            echo '<li class="cart-itm">';
            echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">&times;</a></span>';
            echo '<div class="p-price">'.$currency.$obj->price.'</div>';
            echo '<div class="product-info">';
            echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
            echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
            echo '<div>'.$obj->product_desc.'</div>';
            echo '</div>';
            echo '</li>';
            $subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
            $total = ($total + $subtotal);
 
            echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
            echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
            echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
            echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
            $cart_items ++;
            
        }
        echo '</ul>';
        echo '<span class="check-out-txt">';
        echo '<strong>Total : '.$currency.$total.'</strong>  ';
        echo '</span>';
        echo '</form>';
        
    }else{
        echo 'Your Cart is empty';
    }
?>

That's it then that you, to have a true basket, then there are many issues and details to be added, however, you need to master the basic steps shown in this lesson and, thereafter, may raise up as we wish. If you have any questions, do not hesitate to leave a message in the form of comments offline.

Good luck!

 

Creating cart (Shopping Cart) simple with PHP

Creating cart (Shopping Cart) simple with PHP Posted on 01-08-2015  Creating applications or Shopping Cart shopping cart is always the most important part for web workers. With stormy growth of electronic commerce, the increasing number of website sales with all genres appear. 3/10 1125

Comment:

To comment you must be logged in members.

Files with category

  • Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    View: 2899    Download: 0   Comment: 0   Author: none  

    Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    Category: References
    Fields: Other

    0/4 review
    Windows 10 pre-installed Mail application for managing personal email on the device. The latest version of this application but improved a lot and support other email accounts such as Gmail or Yahoo Mail but users almost no "salty" really with this...

  • Step by step instructions to create social networking buttons with CSS3

    View: 2006    Download: 0   Comment: 0   Author: none  

    Step by step instructions to create social networking buttons with CSS3

    Category: References
    Fields: Other

    0.64285714285714/7 review
    CSS3 help web designers have the ability to create buttons (buttons) very nice, today I will share with you two tips decoration for button in your web becomes radiant beauty that no need to use photoshop.

  • You should understand the CSS Box Shadow

    View: 2139    Download: 0   Comment: 0   Author: none  

    You should understand the CSS Box Shadow

    Category: References
    Fields: Other

    1.2083333333333/12 review
    Effects his shadow was introduced in the previous article, however, in this article, I will guide more specific about shadow attributes, you try it with anything. First we try to learn css following paragraph:

  • How to do button movement with beautiful CSS3

    View: 1828    Download: 0   Comment: 0   Author: none  

    How to do button movement with beautiful CSS3

    Category: References
    Fields: Other

    0/5 review
    Previously to create motion effects button, you must draw the button in photoshop, then switched to flash to make it possible to move. But now you need not spend too much time doing it, all because of the emergence of CSS3.

  • Create a dropdown menu with CSS3 effects with beautiful transtions

    View: 2108    Download: 0   Comment: 0   Author: none  

    Create a dropdown menu with CSS3 effects with beautiful transtions

    Category: References
    Fields: Other

    0.40909090909091/11 review
    More of the dropdown menu you want to introduce to you, this will have the effect menu transitions (converted background of menu background from pale to dark). This menu works well on browsers like FF, Chrome, Safary, but unfortunately did not work...

  • How to hack css for all browsers you should know

    View: 1733    Download: 0   Comment: 0   Author: none  

    How to hack css for all browsers you should know

    Category: References
    Fields: Other

    1.5/9 review
    In the process of web design, which makes it the most headaches is how to design web pages that you can run on the browser. Especially when clients use the old as IE6 browser such. However, with this article, you will easily edit interface runs well...

  • Create Accordion with extremely beautiful CSS3

    View: 2163    Download: 0   Comment: 0   Author: none  

    Create Accordion with extremely beautiful CSS3

    Category: References
    Fields: Other

    0.75/6 review
    Accordion is a technique that helps you shortened the content that you want displayed on the website. It is often used for the display of submenus. In addition you can also use it for content, images. Before applying this procedure, you have to use...

  • Create the effect Hovercho images with Webkit and CSS3 is great

    View: 1850    Download: 0   Comment: 0   Author: none  

    Create the effect Hovercho images with Webkit and CSS3 is great

    Category: References
    Fields: Other

    0.9/5 review
    WebKit is one open source application framework provides the necessary components built one for your web browser. Along with CSS3, cả have contributed to very nice effect những previously only using JavaScript or JQuery thực beige.​

 

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd