In-depth PHP shopping cart module function analysis (function explanation, attached source code) _php Tutorial

Source: Internet
Author: User
Tags define session php template preg smarty template
One, Shopping cart overview
A shopping cart is a place where consumers provide a temporary store of goods for online shopping. Its main features include: adding items, deleting items, changing the number of items, subtotal items, total amount of merchandise and emptying the cart, including generating orders, order printing, order previews, submitting orders, and cancelling purchases.
The operation flow of the shopping cart: First, login to the website to browse the goods; then, purchase the specified goods, go to the shopping cart page, on this page can be implemented to change the number of items, delete goods, empty shopping cart, continue shopping, etc., finally, fill in the consignee information, generate orders, order printing, preview, submit orders and other operations

two, hot key technology
Installation configuration of the 1,smarty module
Smarty is a php template engine written in PHP that divides an application into two parts: View and Logical control. The UI and PHP code are going to be separated. PHP does not have a built-in Smarty template class, it needs to be downloaded and configured separately, and Smarty requires a minimum PHP version of 4.0 on the server. 6. PHP Smarty can be downloaded in http://www.smarty.net/download. Unzip the 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 and rename it. Rename the Libs directory to smarty here. To this smarty template installation is complete.
configuration of the 2,smarty template
(1) First determine the location of the Smarty directory. Because the Smarty class library is generic, each project will be used basically, in order to invoke convenience, the habit of smarty placed in the root directory.

(2) New 4 directories templates, Templates_c, configs, and cache for storing different files. The new 4 directory location is optional, as long as the configuration file path is set correctly.

(3) Create a configuration file. As long as you apply the Smarty template, you must include the Smarty class library and related information. It is unrealistic to write each page once, and the best way is to write the configuration information to a file and invoke the configuration file with include. When the profile is created, it is saved in the root directory. The module configuration file config.php code is as follows:
Copy CodeThe code is as follows:
/* Define the absolute path to the server */
Define (' Base_path ', ' E:\PHPservices\\ ');
/* Define the Smarty directory of the Jedi you path */
Define (' Smarty_path ', ' sourcecode\12\01\\ ');
/* Load the Smarty class library file */
Require Base_path. Smarty_path. ' smarty\smarty.class.php ';
/* Instantiate a Smarty Object */
$smarty = new Smarty;
/* Define paths for 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/';
/* Define 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 most important feature of the Smarty template is the separation of static and dynamic applications, separating the UI from the PHP code. The following is a description of the Smarty template in the implementation of static and dynamic separation process commonly used techniques.
(1) Get the value of the template variable in the PHP code in the UI
The first thing to determine is the Smarty template, which uses ' <{' and '}> '. It is also applied to some smarty built-in functions, such as section, PHP, if, ElseIf, else, and so on.
A) The section function iterates through the data in the array. Each {section} tag must appear in pairs with the closed label {/section}, and the parameter name and loop are required options.
Names name is any combination of letters, numbers, and underscores that can be nested but must be guaranteed to be nested name unique.
A variable loop (usually an array) determines the number of times a loop executes, for example, when a variable needs to be output within a section loop, the variable must be preceded by a bracket, and the name variable is enclosed in parentheses.
For example:
Copy CodeThe code is as follows:
<{section name=data loop= $myrow}>

<{$myrow [data].tb_commodity_name}>
<{$myrow [data].tb_commodity_price}>

&LT;{/SECTION}&GT;B) PHP tags are directly embedded in the template php script, the format of the label is "<{php}>" and "<{/php}>".
c) The IF, else statements are also supported in the Smarty template, and several features are added to accommodate the template engine. If and/if must appear in pairs, you can use else and elseif words, you can use the following conditions modifiers: 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, = = =,! =, >, <, <=, >=. When using modifiers, you must separate the variables or constants with a space. Examples are as follows:
<{if $isShow = = "F"}>

Sorry, there is no product information in your shopping cart!

<{else}>
<{section name=data loop= $myrow}>

<{$myrow [data].tb_commodity_name}>
<{$myrow [data].tb_commodity_price}>

<{/section}>
<{/if}>

(2) Define template variables in PHP code, assign values to template variables
The data in the UI is from the template variables defined in the PHP code. In PHP code, the completion of the PHP code, the value of the output will be assigned to a template variable, and finally the template page to output.
A) The assignment of a template variable is done by 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 for applying the Assign () function is as follows:
$smarty->assign ("Myrow", $array); Using the Assign method to write data in an array $array to Myrow B) The template page is specified by the display method, with the following syntax:
void display (String template[,string cache_id[,string compile_id])
The method is used to specify the template page, where the first required parameter is the type and path of the specified legal template resource, the 2nd optional parameter specifies a cache number, and the 3rd optional parameter specifies a compilation number, and then a template is compiled into a different version for use. Key to application of display methodThe code is as follows:
$smarty->display ("Index.tpl"); Specify the template page to output 3,session shopping cart creation
Session shopping cart is mainly used to implement the session variables. The so-called shopping cart is the 2 session variables created through the Session_register () function, where Goodsid stores the number of id,goodsnum stores of the commodity. The following code is created for the session shopping Cart:
Copy CodeThe code is as follows:
Session_Start (); Initializing Session Variables
Session_register ("Goodsid"); Define session variables for storing commodity IDs
Session_register ("Goodsnum"); Define session variables to store the number of items purchased
?>

The Session_register () function adds a session variable to the entire domain range. Syntax: Boolean session_register (string name);
The parameter name is used to specify the name of the new session variable.
4, using array function to determine whether the shopping cart has a specified product
To avoid repeating additions to your shopping cart, make a judgment on the items you add and the items stored in your cart.
A) Apply the explode () function to convert the string stored in the GOODSID variable to the array with 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 be, to split the strings. Limit: optional, which specifies the maximum number of array elements returned. If the limit parameter is set, the returned array contains a maximum of limit elements, and the last element will contain the remainder of the string. If the limit parameter 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 item is already in the shopping cart, otherwise the item's ID is added to the cart.

The In_inarray () function searches the array for the given value. Returns true if found, otherwise false.
Syntax: BOOL In_array (mixed Value,array array[,bool type])
parameter Description:
Value: Required to specify the values to be searched in the array
Array: Must, specify the arrays to search.
Type: optional, if set to true, checks whether the searched data is the same as the type of the array.
In the shopping cart module, the code that determines whether the specified item exists in the cart is as follows:
Copy CodeThe code is as follows:
Session_Start (); Initializing Session Variables
Session_register ("Goodsid"); Define session variables for storing commodity IDs
Session_register ("Goodsnum"); Define session variables to store the number of items purchased
if ($_session["Goodsid"]== "" && $_session["Goodsnum"]== "") {//Determine if the SESSION variable is empty
$_session["Goodsid"]=$_get["id"]. " @"; If the session variable is empty, it is assigned the ID of the product and separated by @
$_session["Goodsnum"]= "1@"; If the session variable is empty, it is assigned a value of 1 and is delimited by @
}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 @ delimiter.
if (In_array ($_get["id"], $array)) {//If the specified ID exists in the interpretation array
echo "";
Exit
}
If the specified ID does not exist in the array, then the item has not been placed in the cart
$_session["Goodsid"].=$_get["id"]. " @"; Add this item to your shopping cart
$_session["Goodsnum"].= "1@"; Change the number of items
}
echo "";
?>

5. Verify that the input quantity value is valid
In the Preg_match () function, determine whether the value of the number of items submitted conforms to the standard of the regular expression, or if it is valid, the prompt message is given. The program key code is as follows:
Copy CodeThe code is 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 = = "") {//Determine if the committed value is empty
echo "";
Exit
}else if (!preg_match ($preg, $num, $str)) {//To determine if the submitted data is a positive integer
echo "";
Exit
}

The Preg_match () function searches the string for all content that matches the given regular expression and returns true if it exists, otherwise false. The syntax is as follows:
Syntax: int preg_match (string pattern,string sbuject[,array Matches[,int flags])
parameter Description:
Pattern: Necessary parameters, regular expressions to match
Subject: Required parameter, input string matches: Optional parameter. An array of output search results, such as $out[0] will contain results that match the entire pattern, $out [1] will contain results that match the sub-patterns in the first captured parentheses, and so on
Flags: Optional parameter, tag: Preg_offset_capture, returns a common-dependent string offset for each occurrence of the matching result page

third, the function implementation process
1, add Product function
The Add Product feature is implemented by first creating a shopping cart and then adding items (item IDs) to the shopping cart based on the item ID ($_get[id]) that is passed as the "purchase" link in the product Display page, and does not allow repeated additions. The operation to add items to the shopping cart is done through the by_commodity.php file.
First, create a shopping cart.
Then, determine whether the shopping cart is empty, if it is empty, the product ID and quantity added to the shopping cart, if not empty, you want to determine whether the ID of the added item already exists in the shopping cart, if there is not repeated add, otherwise the product ID added to the shopping cart.
Add the Product program code as follows:
Copy CodeThe code is as follows:
Header ("content-type:text/html;charset= utf-8");
Session_Start (); Initializing Session Variables
Session_register ("Goodsid"); Define session variables for storing commodity IDs
Session_register ("Goodsnum"); Define session variables to store the number of items purchased
if ($_session["Goodsid"]== "" && $_session["Goodsnum"]== "") {//Determine if the SESSION variable is empty
$_session["Goodsid"]=$_get["id"]. " @"; If the session variable is empty, it is assigned the ID of the product and separated by @
$_session["Goodsnum"]= "1@"; If the session variable is empty, it is assigned a value of 1 and is delimited by @
}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 @ delimiter.
if (In_array ($_get["id"], $array)) {//If the specified ID exists in the interpretation array
echo "";
Exit
}
If the specified ID does not exist in the array, then the item has not been placed in the cart
$_session["Goodsid"].=$_get["id"]. " @"; Add this item to your shopping cart
$_session["Goodsnum"].= "1@"; Change the number of items
}
echo "";
?>

2, remove the product function in the shopping cart implementation
Deleting items in your shopping cart is performed according to the item ID ($_get[id]) that is passed in the "delete this item" hyperlink. In the delete_commodity.php file, the operation to delete the item in the shopping cart is performed based on the value passed by $_get[id].
First, get the value passed by $_get[id]. Then, apply the explode () function, write the item ID and the number of data stored in the session variable into an array, and use @ as the delimiter.
Next, the Array_search () function is applied to get the key name of the specified ID item in the array, and the specified data in the array is empty based on the obtained key name.
Finally, the empty data that is re-assigned in the array is written to the shopping cart to complete the removal of the specified item in the cart.
Copy CodeThe code is as follows:
Session_Start (); Initializing Session Variables
Require ("config.php"); Connecting Smarty Templates
$id =$_get["id"]; Get the ID of the item you want to delete
$arrayid =explode ("@", $_session["Goodsid"]); Converts a string of item IDs stored in the shopping cart into an array
$arraynum =explode ("@", $_session["Goodsnum"]); Converts a string of the number of items stored in the shopping cart into an array
$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 shopping cart
$_session["Goodsnum"]=implode ("@", $arraynum); Re-add the data in the array to the shopping cart
echo "";
$smarty->display ("Shopping_car.tpl");
?>

The value of the before delete $_session["Goodsid"] is "3@2@5@", and the value of $_session["Goodsid" after $id=5 is removed, so there is extra data @ in the SESSION.
Workaround:
Copy CodeThe code is as follows:
Session_register ("goods"); Creating a Session Array
$id =$_get[' id '];
$arraygoods =$_session["goods"];
if ($_session["goods"]== "") {
$_session["Goods" [$id]= "$id, 1"; Save the item according to the product ID, the key name is $id, the key value is $id,1 (item ID and purchase quantity, the default purchase quantity is 1)
}else{
if (Array_key_exists ($id, $_session["goods")) {
echo "";
Exit
}
$_session["Goods" [$id]= "$id, 1";
}
?>

The product information is saved as an array, [4] = 4, 4. The key name is the product ID, and the value is the key name and the number of items purchased. Add Delete Product only need to find the corresponding product modification information according to the ID number.
Copy CodeThe code is as follows:
Array
(
[4] = + bis
[3] = 3,5
[1] = 1,10
[2] = 2,1
)

3, the realization of generating order function
The Generate order function is to read out the completed order information from the database, re-integrate its content, form an order pattern, and achieve the function of order printing and order preview. The operation of the order generation is done through two files, one reading the data from the database, assigning the required data to the specified Smarty template variable, and specifying the template page.
Copy CodeThe code is as follows:
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 if ($array [$i]!= "") {
$sqlcart =mysql_query ("select * from tb_commodity where tb_commodity_id= '". $array [$i]. "'", $conn);
$infocart =mysql_fetch_array ($sqlcart); Reading data from a database
$totalprices = $infocart ["Tb_commodity_price"]* $arraynum ["$i"]; Calculate the total Price
Array_push ($infocart, $arraynum ["$i"]); Writes the purchased quantity of data to the returned array in the database
Array_push ($infocart, $totalprices); Writes the purchased quantity 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) {//Determine if 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

http://www.bkjia.com/PHPjc/327863.html www.bkjia.com true http://www.bkjia.com/PHPjc/327863.html techarticle One, Shopping cart Overview Shopping cart is a place for consumers to provide a temporary storage of goods in online shopping. Its main functions include: Add a product, delete a product, change the quantity of a product , a trader ...

  • Related Article

    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.