PHP Shopping Cart session (non-frame)

Source: Internet
Author: User

This is my interview in the face of the question, simple to write shopping cart function, the requirements are:

1, write a simple front desk

2, users can use the shopping cart before logging in

3. Cookies may not be used

There are three solutions available for the time being:

1. Cookies

2. Session

3. Database

The main logic of the shopping cart is to use the session to identify different users ' respective shopping carts so that users can log in and save their own shopping carts. The flowchart is as follows:


The code for each file is as follows:

shop_list.php
<?php/* shop_list.php * The main function of the file for the product display * and the user needs to add products to the shopping cart *///connection database include ' mysql_connect.php '; session_start (); ><br><a style= "font-size:150%;color:red" > Current User: <?php if (isset ($_session[' user_name '])) echo $_session[' user_name '.    "     ";    else echo ' not logged in '; ?> <a href= "login.php" > (login) </a> <?php}?> </a><a style= "Font-size:150%;color: Blue "href=" shop_cart.php "> Products </a><table border=" 1 "height=" 400px "width=" 400px "> <td style=" fo Nt-size:120%;color:blue;text-align:center "> Commodity id</td> <td style=" font-size:120%;color:blue;text-align  : Center "> Product name </td> <td style=" Font-size:120%;color:blue;text-align:center "> Number of items </td> &LT;TD style= "Font-size:120%;color:blue;text-align:center" > Commodity price </td> <td style= "font-size:120%;color:blue;t Ext-align:center "> Operations </td><?php//querying the database and processing the result set $sql =" SELECT * from goods order BY ' goods_id ' "; $result = mysql_query ($sql, $conn); while ($row = Mysql_fetch_array ($result)) {?> <tr> &LT;TD width= "50px" ><?php echo $row [' goods_id ']?></td> <td ><?php echo $row [' Goods_na Me ']?></td> <td ><?php echo $row [' Goods_num ']?></td> <td ><?ph                P echo $row [' Goods_price ']?></td> <td style= "Font_size:150%;color:red;text-align:center" > <a href= "shop_cart.php?goods_id=<?php echo $row [' goods_id '];? >&goods_name=<?php echo $row [' Go Ods_name '];?> "> Add to Cart </a> </td> </tr><?php}?></table>




shop_cart.php
<?php/* shop_cart.php * The main function of the file is to accept the user from the shop_list.php by the get way to add the shopping cart product data * and create the session data of the product, or update the session of the user needs the number of items * Finally jump to the shopping cart content page buy.php * */include ' mysql_connect.php '; The file//main logic for the introduction of MySQL connection method is: Using session storage to add to the shopping cart data, so as to distinguish each individual user's shopping cart,//and the session store content is a two-dimensional array, in the format of "' Product Name '" [' The specific data of the product ']//the specific data of the product has two 1, the user chooses the Product ID 2, the user chooses the quantity//session_start (); Open Session$get_name = $_get["Goods_name"];     Extract submitted from GET goods_name$get_id = $_get["goods_id"];    Extract submitted from Get Goods_id$arr = $_session[' Shop_cart ']; Assign the SESSION to a two-dimensional array//$_session[' Shop_cart ']=array ($GET _name=>array (' goods_id ' = _id, ' goods_num '));// The two-dimensional array is stored in the SESSION//$arr =$_session["Shop_cart"];//now determine whether the contents of the two-dimensional array $arr the existence of the product is added shopping cart name to determine whether the item is added to the shopping cart for the first time,//If it is the first time, Add the entire data of the product to the two-dimensional array that created the session for the product//otherwise it is not the first time, then the number of goods_num in the two-dimensional data in the session year of the product is increased to 1 if (array_key_exists ($GET _name, $arr)    {//The item has been added to the cart for a quantity plus 1 operation $a = $arr [$GET _name][' goods_num '] + +; Echo ' Existence of the product '. $arr [$GET _name][' Goods_num '];} else {//the item is added to the shopping cart for a new Item $sql = "SELECT * FROM goods where' goods_id ' = '.  $GET _id;    Create a SQL statement $result = mysql_query ($sql) to find specific information about the corresponding product; Specific information for the product find the result $row = Mysql_fetch_array ($result);//arr0 is an array of new shopping carts to add an existing shopping cart array arr $arr 0 = Array ($GET _name = Array (' Go ods_id ' + $GET _id, ' goods_num ' + 1, ' goods_name ' + $GET _name, ' goods_price ' = $row [' Goods_price ']);//arr    0 assignment to arr1 foreach ($arr 0 as $key = + $value) {$arr [$key] = $value; }}//Add the completion, re-update the two-dimensional array to session$_session[' shop_cart '] = $arr;//Successfully added complete, jump page header ("location:buy.php"); Skip to Shopping cart content interface?>
buy.php
<?php/* buy.php * This file main function for shopping cart content display * And according to the user choose to checkout shopping cart to call finish.php file *///open Sessionsession_start ();  Open Session$arr = $_session[' Shop_cart ']; Read a two-dimensional array from the session? ><br><a style= "font-size:150%;color:red" href= "buy.php" > Current User: <?php if (Isset (    $_session[' user_name ')) {echo $_session[' user_name '];    } else {echo ' not logged in '; }? ></a><a style= "Font-size:150%;color:blue" href= "shop_cart.php" > Shopping cart status </a><table border= " 1 "height=" 400px "width=" 400px "> <td style=" font-size:120%;color:blue;text-align:center "> Merchandise ID&LT;/TD&G    T &LT;TD style= "Font-size:120%;color:blue;text-align:center" > Product name </td> <td style= "Font-size:120%;color: Blue;text-align:center "> Product quantity </td> <td style=" Font-size:120%;color:blue;text-align:center "> Commodity price            </td> <?php//traversing a two-dimensional array read the product information added to the shopping cart foreach ($arr as $v + $val) {?> <tr> &LT;TD width= "50px" ><?php echo $val [' goods_id ']?></td> <td ><?php echo $val [' Goods_name ']?></td> &LT;TD ><?php echo $val [' Goods_num ']?></td> <td ><?php echo $val [' Goods_price ']?> </td> </tr> <?php} ></table><form name= "MyForm" method= "POST" action= "finish.php" &G    T <input type= "hidden" name= "goods_id" value= "$val [' goods_id ']"/><br/> <input type= "hidden" name= "goods _name "value=" $val [' Goods_name '] "/><br/> <input type=" hidden "name=" Goods_num "value=" $val [' Goods_num '] "/><br/> <input type=" hidden "name=" Goods_price "value=" $val [' goods_price '] "/> <input type=" SUBM It "name=" sub "style=" font-size:200%;color:red "value=" Checkout cart "/></form><form ></form>
finish.php
<?phpinclude ' mysql_connect.php ';//through session[' user_name ') to determine whether to log in. If logged in the data is written to the database, and prompt to successfully jump to the product display page//If not logged in, prompted to sign in, and jump to the login page session_start ();   Open Session$arr = $_session[' Shop_cart '];  Read the two-dimensional array from the session if (Isset ($_session[' user_name ')) {    //already logged in, extracting data from the session to write to database    foreach ($arr as $v = $ val) {        $values = $val [' goods_id ']. ",'" . $val [' Goods_name ']. "'," . $val [' Goods_num ']. "," . $val [' Goods_price ']. ",'" . $_session[' user_name '. "'";        $sql = "INSERT INTO ' buy ' (' buy_goods_id ', ' buy_goods_name ', ' buy_goods_num ', ' buy_goods_price ', ' user_name ') VALUES ($ values); ";        $rs = mysql_query ($sql);    }    if ($rs) {        echo "settlement success!!! Returning home! ";        Header ("refresh:2;url=shop_list.php"); Jump after two seconds    } else {        echo ' settlement failed, returning to cart! " . Mysql_errno ();        Header ("refresh:2;url=buy.php"); Two seconds after the jump    }} else {    echo "Please log in before you settle!" ";    Header ("refresh:2;url=login.php");}? >
login.php



mysql_connect.php
<?php/* mysql_connect.php * The main function of this file is MySQL connection *///    Connection database    $conn = mysql_connect (' localhost ', ' root ', ' 12345 ');    mysql_select_db (' ShoppingCart ', $conn);    $conn _rs = mysql_query (' Set names UTF8 ');    if ($conn _rs)    //echo "MySQL connection succeeded!";        Echo ';    Else die        (' MySQL connection error '. Mysql_error ());? >

Finally, the required database tables are:
Shoppingcart.sql
--shoppingcart.sql--the file is to record the various tables of the database to be established by this mall and the data to create the databases ' ShoppingCart ';--goods tables drop table IF EXISTS ' Goods '; CREATE TABLE ' Goods ' (' goods_id ' tinyint (4) unsigned not NULL auto_increment PRIMARY KEY, ' goods_name ' varchar () N OT null COMMENT ' commodity name ', ' Goods_num ' smallint (6) unsigned not NULL COMMENT ' goods remaining ', ' Goods_price ' smallint (6) Unsi    gned not NULL COMMENT ' commodity price ') Engine=myisam auto_increment=1 DEFAULT charset=utf8;--user table drop table IF EXISTS ' user '; CREATE TABLE ' User ' (' user_id ' tinyint (4) unsigned not NULL auto_increment PRIMARY KEY, ' user_name ' varchar (NO) Null COMMENT ' user name ', ' user_pwd ' varchar (not NULL COMMENT ' user password ') engine=myisam auto_increment=1 DEFAULT Charset=utf8;  --order Form CREATE table ' Buy ' (' buy_goods_id ' tinyint (4) unsigned not NULL, ' buy_goods_name ' varchar (a) NOT null COMMENT ' Commodity name ', ' Buy_goods_num ' smallint (6) unsigned not NULL COMMENT ' merchandise purchase quantity ', ' Buy_goods_price ' smallint (6) unsigned NO T NULL COMMENT ' commodity price ', ' user_Name ' varchar ' not NULL COMMENT ' Order submitter ') Engine=myisam auto_increment=1 DEFAULT charset=utf8;--user table insert INTO ' Goods ' V Alues (1, ' Nokia ', 100,2000); insert INTO ' Goods ' values (2, ' Samsung ', 150,3000); insert INTO ' Goods ' values (3, ' Apple ', 200,4000) insert INTO ' user ' values (1, ' Tim ', ' 123 '), insert INTO ' user ' values (2, ' Jack ', ' 123 ') and insert into ' user ' values ( 3, ' Tom ', ' 123 ');


Summary: In fact, the logic of shopping cart is very simple, mainly to solve how to identify the identity of each user not logged in, there are three solutions, namely 1, Cookie 2, Session 3, the database this is easy to solve with the session, The advantage of the relative cookie solution is that the function of the shopping cart will not be invalidated because the user has disabled the cookie function of the machine; The session put the data in the server, the security also has a certain increase; But the session is not completely without shortcomings, if the number of concurrent users, Generates a large number of sessions on the server, consuming the server's resources and impacting the performance of the server.



PHP Shopping Cart session (non-frame)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.