One, Shopping cart overview
Shopping cart is a place for consumers to provide a temporary store of merchandise on the Internet. Its main functions include: adding goods, deleting goods, changing the quantity of goods, subtotal merchandise, total amount of goods and emptying the shopping cart, including generating orders, order printing, order previews, submitting orders and canceling shopping.
The operation process of the shopping cart: First of all, log in to the site to browse the merchandise; then, purchase the specified goods, enter the shopping cart page, on which you can change the number of items, delete the goods, empty the cart, continue shopping, etc. finally, fill in the consignee information, generate orders, print orders, preview, submit orders and other operations.
Second, hot Key technology
Installation configuration for 1,smarty modules
Smarty is a php template engine written using PHP that divides an application into two parts: View and Logical control. Separating the UI from the PHP code. PHP does not have a built-in Smarty template class that needs to be downloaded and configured separately, and Smarty requires a minimum PHP version of 4.0.6 on the server. PHP Smarty can be downloaded in http://www.smarty.net/download. Unzip the compressed package, which has a libs directory containing all the core files of the Smarty class library. Includes smarty.class.php, smarty_Compiler.class.php, config_File.class.php and Debug.tpl 4 files, as well as internals and plug-ins two directories.
Copy the Libs directory to the server root directory and rename it. Here, rename the Libs directory to Smarty. The Smarty template has been installed to complete.
Configuration of 2,smarty templates
(1) First determine the location of the Smarty directory. Because the Smarty class library is generic, each project is basically used, in order to invoke convenience, the habit of smarty placed in the root directory.
(2) New 4 directory templates, Templates_c, configs, and cache for storing different files. The new 4 directory location is optional, as long as the profile path is set correctly.
(3) Create a configuration file. As long as you apply the Smarty template, be sure to include the Smarty class library and related information. It is not realistic to write the configuration on every page, the best way is to write the configuration information to a file and invoke the configuration file with include. The configuration file is saved in the root directory when it is created. The module configuration file config.php code is as follows:
Copy Code code as follows:
<?php
/* Define the absolute path of the server * *
Define (' Base_path ', ' E:\PHPservices\\ ');
/* Define the Smarty directory of the Jedi your path * *
Define (' Smarty_path ', ' sourcecode\12\01\\ ');
/* Load Smarty Class library file * *
Require Base_path. Smarty_path. ' smarty\smarty.class.php ';
/* Instantiate a Smarty Object * *
$smarty = new Smarty;
/* Define the path of each directory/*
$smarty->template_dir = Base_path. Smarty_path. '. /';
$smarty->compile_dir = Base_path. Smarty_path. ' templates_c/';
$smarty->config_dir = Base_path. Smarty_path. ' configs/';
$smarty->cache_dir = Base_path. Smarty_path. ' cache/';
/* Definition delimiter * *
$smarty->left_delimiter = ' <{';
$smarty->right_delimiter = '}> ';
/* Use the Smarty assignment method to send a pair of child names/methods to the template * *
?>
3,smarty template static and dynamic separation
The biggest feature of the Smarty template is the separation of the UI from the PHP code by implementing static and dynamic applications. The following describes the Smarty template in the implementation of static and dynamic separation of the common technology.
(1) Get the value of the template variable in the PHP code in the UI
The first thing to determine is the definition of the Smarty template, where the ' <{' and '}> ' are used. Also applied to some Smarty function section, PHP, if, ElseIf, else and so on.
A the section function is used to traverse the data in the array. Each {section} label must appear in pairs with the closed label {/section}, and the parameter name and loop are required.
A name is any combination of letters, numbers, and underscores that can be nested but must guarantee that the nested name is unique.
The variable loop (usually an array) determines the number of times the loop executes, for example, when you need to output a variable within a section loop, you must precede the variable with the brackets, and enclose the name variable in brackets.
For example:
Copy Code code as follows:
<{section name=data loop= $myrow}>
<tr>
<TD width= "bgcolor=" "#FFFFFF" ><{$myrow [data].tb_commodity_name}></td>
<TD bgcolor= "#FFFFFF" ><{$myrow [data].tb_commodity_price}></td>
</tr>
<{/section}>b PHP tags are directly embedded in the template PHP script, the label format is "<{php}>" and "<{/php}>."
c The IF, else statements are also supported in Smarty templates, and several features are added to fit the template engine. If and/if must appear in pairs, you can use else and elseif; You can use the following conditions to modify the words: EQ, NE, neq, GT, LT, LTE, Le, GTE, GE, is even, is odd, is not even, is not odd, not, MoD, div by, even by, odd by, = =,!=, >, <, <=, >=. You must separate the variables or constants with spaces when you use modifiers. Examples are as follows:
<{if $isShow = = "F"}>
<tr>
<TD height= "colspan=" "5" bgcolor= "#FFFFFF" ><div align= "center" > Sorry, there is no product information in your shopping cart! </div></td>
</tr>
<{else}>
<{section name=data loop= $myrow}>
<tr>
<TD height= align= "center" bgcolor= "#FFFFFF" ><{$myrow [data].tb_commodity_name}></td>
<TD height= "bgcolor=" "#FFFFFF" ><div align= "center" ><{$myrow [data].tb_commodity_price}></ Div></td>
</tr>
<{/section}>
<{/if}>
(2) Define template variables in PHP code and assign values to template variables
The data in the UI is derived from the template variables defined in the PHP code. In the PHP code, complete the writing of PHP code, the value of the output will be assigned to a template variable, and finally make a template page for output.
A to assign a value to a template variable through a custom function assign (), where the first parameter is the variable name being assigned, and the second parameter is the value assigned to the variable. The key code to apply the Assign () function is as follows:
$smarty->assign ("Myrow", $array); The Assign method of writing data from an array $array to B in myrow specifies that the template page is done by means of the display method, with the following syntax:
void display (String template[,string cache_id[,string compile_id])
The method is used to specify a template page where the first required parameter is the type and path that specifies a legitimate template resource, the 2nd optional parameter specifies a cache number, and the 3rd optional parameter specifies a compilation number, which is used when compiling a template into a different version. The key to the application of display method
The code is as follows:
$smarty->display ("Index.tpl"); Specify the template page to output 3,session the creation of a shopping cart
The session shopping cart mainly uses the session variable to realize. The so-called shopping cart is the 2 session variables created by the Session_register () function, where the number of Id,goodsnum stores that store the goods is goodsid. The session shopping cart creates the following code:
Copy Code code as follows:
<?php
Session_Start (); Initializing the session variable
Session_register ("Goodsid"); Define session variables to store commodity IDs
Session_register ("Goodsnum"); Define a session variable to store the number of items purchased
?>
Session_register () function that adds a session variable to the entire domain. Syntax: Boolean session_register (string name);
The parameter name specifies the name of the new session variable.
4, using the array function to determine whether a shopping cart exists a specified product
To avoid duplication of items in a shopping cart, make a judgment on the added goods and the items stored in the shopping cart.
(a) Apply the explode () function to convert the string stored in the GOODSID variable to the array by using @ as the delimiter.
The explode () function, which returns an array of strings, each of which is a substring separated by separator as a boundary point.
syntax: Array explode (string separator,string string,[ing limit])
parameter Description:
Separator: must, specify where to split the string. Cannot be an empty string, otherwise explode () returns false
String: Must, the strings to be split. Limit: Optionally, specify the maximum number of array elements returned. If the limit parameter is set, the returned array contains up to limit elements, and the last element will contain the remainder of the string. If the limit argument is a negative number, all elements except the last-limit element are returned.
b) the In_array () function determines whether the specified product ID exists in the array, and if so, the product is already in the shopping cart, or if the product does not exist, the ID of the item is added to the cart.
The In_inarray () function searches the array for a given value. Returns true if found, otherwise returns false.
Syntax: bool In_array (mixed Value,array array[,bool type])
parameter Description:
Value: Must, specify the values to search for in the array
Array: Must, specify the arrays to search for.
Type: optional, and if set to True, check that the search data is the same as the type of the array.
In the shopping cart module, the code that determines whether a specified item exists in the shopping cart is as follows:
Copy Code code as follows:
<?php
Session_Start (); Initializing the session variable
Session_register ("Goodsid"); Define session variables to store commodity IDs
Session_register ("Goodsnum"); Define a session variable to store the number of items purchased
if ($_session["Goodsid"]== "" && $_session["Goodsnum" ") {//To determine whether the session variable is empty
$_session["Goodsid"]=$_get["id"]. " @"; If the session variable is empty, the value is assigned to the ID of the product and is separated by the @
$_session["Goodsnum"]= "1@"; If the session variable is empty, it is assigned a value of 1 and is separated by the @
}else{//If the session variable is not empty
$array =explode ("@", $_session["Goodsid"]); The data in the session variable is written to the array with the @ as the delimiter
if (In_array ($_get["id"], $array)) {//If the specified ID exists in the interpretation array
echo "<script>alert" (' The product has been put into the shopping cart!) '); History.back ();</script> ";
Exit
}
If the specified ID does not exist in the array, the item is not yet in the cart
$_session["Goodsid"].=$_get["id"]. " @"; Add this item to the shopping cart
$_session["Goodsnum"].= "1@"; Change the number of items
}
echo "<script>window.location.href= ' shopping_car.php ';</script>";
?>
5, verify that the value of the input quantity is valid
In the Preg_match () function, the value of the number of items submitted is judged to conform to the standard of the regular expression, and if it is valid, a hint will be given. The program key code is as follows:
Copy Code code as follows:
$id =$_post["id"]; Get Product ID
$num =$_post["Goodsnum"]; Get the number of items
$preg = "/^[0-9]*[0-9]$|^[0-9]*[0-9]$/"; Writing Regular Expressions
if ($num = = "") {//To determine whether the submitted value is null
echo "<script>alert (' number cannot be empty! '); History.back ();</script> ";
Exit
}else if (!preg_match ($preg, $num, $str)) {//To determine whether the submitted data is a positive integer
echo "<script>alert (' number can only be positive integer! '); History.back ();</script> ";
Exit
}
Preg_match () function that searches the string for all occurrences of the given regular expression, returns True if it exists, or returns false. The syntax is as follows:
syntax: int preg_match (string pattern,string sbuject[,array Matches[,int flags]])
parameter Description:
Pattern: Required parameters, matching regular expressions
Subject: Necessary parameters, input string matches: Optional parameters. An array of the output's search results, such as $out[0], will contain results that match the entire pattern, $out [1] will contain the results that match the child pattern in the first captured bracket, and an analogy
Flags: Optional parameters, Tags: preg_offset_capture, returns a shared string offset for each occurrence of the resulting page
Third, the function realization process
1, add the product function
The principle of adding a product is to create a shopping cart first, and then add the product (Product ID) to the shopping cart based on the commodity ID ($_get[id) passed in the "buy" link in the product Display page, and not allow duplicate additions. The operation of adding items to the shopping cart is done through the by_commodity.php file.
First, create a shopping cart.
Then, determine if the shopping cart is empty, if it is empty, add the ID and quantity of the item to the cart, or if it is not, determine if the item ID is already in the shopping cart, or add the item ID to the cart if it exists.
Add commodity program code as follows:
Copy Code code as follows:
<?php
Header ("content-type:text/html;charset= utf-8");
Session_Start (); Initializing the session variable
Session_register ("Goodsid"); Define session variables to store commodity IDs
Session_register ("Goodsnum"); Define a session variable to store the number of items purchased
if ($_session["Goodsid"]== "" && $_session["Goodsnum" ") {//To determine whether the session variable is empty
$_session["Goodsid"]=$_get["id"]. " @"; If the session variable is empty, the value is assigned to the ID of the product and is separated by the @
$_session["Goodsnum"]= "1@"; If the session variable is empty, it is assigned a value of 1 and is separated by the @
}else{//If the session variable is not empty
$array =explode ("@", $_session["Goodsid"]); The data in the session variable is written to the array with the @ as the delimiter
if (In_array ($_get["id"], $array)) {//If the specified ID exists in the interpretation array
echo "<script>alert" (' The product has been put into the shopping cart!) '); History.back ();</script> ";
Exit
}
If the specified ID does not exist in the array, the item is not yet in the cart
$_session["Goodsid"].=$_get["id"]. " @"; Add this item to the shopping cart
$_session["Goodsnum"].= "1@"; Change the number of items
}
echo "<script>window.location.href= ' shopping_car.php ';</script>";
?>
2, delete the shopping cart in the realization of the function of goods
The action to delete the item in the shopping cart is performed according to the commodity ID ($_get[id] passed in the "delete this item" hyperlink. In the delete_commodity.php file, the action to delete the item in the shopping cart is performed according to the value passed by $_get[id.
First, get the value passed by $_get[id]. Then, the explode () function is applied to write the data of the commodity ID and quantity stored in the session variable to the array with the @ as the separator.
Next, the Array_search () function is applied to get the key name of the specified ID item in the array, and the data assigned to the array is null based on the obtained key name.
Finally, the empty data that is assigned to the array is written to the shopping cart to complete the deletion of the specified item in the cart.
Copy Code code as follows:
<?php
Session_Start (); Initializing the session variable
Require ("config.php"); Connecting Smarty Templates
$id =$_get["id"]; Get the ID of the item to delete
$arrayid =explode ("@", $_session["Goodsid"]); Converts a string from the item ID stored in the shopping cart into an array
$arraynum =explode ("@", $_session["Goodsnum"]); Converts a string to an array of the number of items stored in the shopping cart
$key =array_search ($id, $arrayid); Gets the data specified in the array and returns the key name
$arrayid [$key]= ""; Assigns the data in the array to null based on the returned key name
$arraynum [$key]= ""; Assigns the data in the array to null based on the returned key name
$_session["Goodsid"]=implode ("@", $arrayid); Re-add the data in the array to the cart
$_session["Goodsnum"]=implode ("@", $arraynum); Re-add the data in the array to the cart
echo "<script>window.location.href= ' shopping_car.php ';</script>";
$smarty->display ("Shopping_car.tpl");
?>
The value of the previous $_session["Goodsid"] is "3@2@5@", and the value of $_session["Goodsid" after the $id=5 is deleted is "3@2@@";
Workaround:
Copy Code code as follows:
<?php
Session_register ("goods"); Create a session array
$id =$_get[' id '];
$arraygoods =$_session["goods"];
if ($_session["goods"]== "") {
$_session["Goods" [$id]= "$id, 1"; Save the product according to the product ID, the key name is $id, the key value is $id,1 (product ID and purchase quantity, default purchase quantity is 1)
}else{
if (Array_key_exists ($id, $_session["goods"])) {
echo "<script>alert" (' The product has been put into the shopping cart!) '); History.back ();</script> ";
Exit
}
$_session["Goods" [$id]= "$id, 1";
}
?>
The product information is stored as an array, [4] => 4, 4. The key name is the commodity ID, and the value is the key name and the number of items purchased. To add a deleted item, you only need to find the corresponding product modification information according to the ID number.
Copy Code code as follows:
Array
(
[4] => 4,4
[3] => 3,5
[1] => 1,10
[2] => 2,1
)
3, to generate the implementation of the Order function
The function of generating order is to read out the order information from the database, reorganize its contents, form an order mode, and realize the function of order printing and order preview. The order-generated operations are done with two files, one reading data from the database, assigning the required data to the specified Smarty template variable, and specifying the template page.
Copy Code code as follows:
<?php
Session_Start ();
Header ("content-type:text/html;charset= utf-8");
Require_once ("conn.php");
Require_once ("config.php");
$array =array (); Define an empty array
$ddnumber =base64_decode ($_get["Ddno"]);
mysql_query ("Set names UTF8");
$sql =mysql_query ("select * from Tb_commodity_order_form where ddnumber= '". $ddnumber. "", $conn);
$info =mysql_fetch_array ($sql);
Array_push ($array, $info); Writes the obtained array value to the new array
$smarty->assign ("info", $array);
$array =explode ("@", $info ["SPC"]);
$arraynum =explode ("@", $info ["SLC"]);
$totalprice = 0; Define Price variables
$arrayinfo =array (); Create an array
for ($i =0; $i <count ($array); $i + +) {
if ($array [$i]!= "") {
$sqlcart =mysql_query ("select * from tb_commodity where tb_commodity_id= '". $array [$i]. "'", $conn);
$infocart =mysql_fetch_array ($sqlcart); Reading data in a database
$totalprices = $infocart ["Tb_commodity_price"]* $arraynum ["$i"]; Calculate the total Price
Array_push ($infocart, $arraynum ["$i"]); Writes the purchased amount of data to the returned array in the database
Array_push ($infocart, $totalprices); Writes the purchased amount of data to the returned array in the database
Array_push ($arrayinfo, $infocart); Press the sorted data into the new array you created
$totalprice + + $infocart ["Tb_commodity_price"]* $arraynum ["$i"]; Calculate the total Price
}
}
Session_unregister ("goods");
if (count ($arrayinfo) >0) {//To determine whether the array is empty
$gnum =count ($arrayinfo);
$smarty->assign ("Isshow", "T");
$smarty->assign ("Gnum", $gnum);
$smarty->assign ("Myrow", $arrayinfo);
$smarty->assign ("Totalprice", $totalprice);
}else{
$smarty->assign ("Isshow", "F");
}
$smarty->display ("Shopping_dd.tpl");
?>
The other is the Shopping_dd.tpl template page, which outputs the data stored in the template variable and generates an order.
Four, source code download: Click to download