Go deep into the function analysis of the PHP shopping cart module (function description, with source code)

Source: Internet
Author: User
Tags php template preg smarty template
This article provides a detailed analysis of the function of the PHP shopping cart module. For more information, see 1. shopping cart overview
A shopping cart is a place for consumers to temporarily store items during online shopping. Its main functions include: add a commodity, delete a commodity, change the commodity quantity, Subtotal of the commodity amount, total commodity amount, and clear a shopping cart; it also includes generating orders, printing orders, previewing orders, submitting orders, and canceling shopping.
Shopping cart operation process: first, log on to the website to browse the product; then, purchase the specified product, enter the shopping cart page, on this page, you can change the number of items, delete the items, clear the shopping cart, and continue shopping. finally, enter the consignee information, generate the order, print the order, preview, and submit the order.

2. key technologies
1. install and configure the Smarty module
Smarty is a PHP template engine written in PHP. it divides an application into two parts: View and logic control. Separating UI and PHP code. PHP does not have a built-in Smarty template class and needs to be downloaded and configured separately. In addition, Smarty requires the PHP version on the server to be 4.0.6 at the lowest. PHP Smarty can be downloaded at http://www.smarty.net/download. Decompress the package. there is a libs directory that contains all the core files of the Smarty class library. The files include smarty. class. php, smarty_Compiler.class.php, config_File.class.php, and debug. tpl, as well as the internals and plug-ins directories.
Copy the libs directory to the root directory of the server and rename it. Rename the libs directory as smarty. The Smarty template has been installed.
2. configure the Smarty Template
(1) First, determine the location of the Smarty directory. Because the Smarty class library is common, it is usually used in every project. for convenience of calling, you are used to placing smarty under the root directory.

(2) create four directories templates, templates_c, configs, and cache to store different files. You can select the four directory locations you have created, as long as the configuration file path is set correctly.

(3) Create a configuration file. As long as the Smarty template is applied, the Smarty class library and related information must be included. It is unrealistic to write the configuration once on every page. The best way is to write the configuration information to a file and call the configuration file through include. After the configuration file is created, it is saved in the root directory. The configuration file config. php code of this module is as follows:

The code is as follows:


/* Define the absolute path of the server */
Define ('base _ path', 'E: \ PHPservices \\');
/* Define your path to the Smarty directory */
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 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 /';
/* Define the delimiter */
$ Smarty-> left_delimiter = '<{';
$ Smarty-> right_delimiter = '}> ';
/* Use the Smarty value assignment method to send a pair of child names/methods to the template */
?>


3. static and dynamic separation of the smarty Template
The biggest feature of the smarty template is the separation of dynamic and static applications, separating the UI and PHP code. The following describes the common technologies used by the Smarty template to implement static/dynamic separation.
(1) obtain the value of the template variable in PHP code in the UI
First, determine the identifier of the Smarty template. here, '<{' and '}>' are used '. In addition, some built-in functions such as section, php, if, elseif, and else of Smarty are also applied.
A) the section function is used to traverse the data in the array. Each {section} tag must be paired with the closed Tag {/section}. the parameter name and loop are required.
The name is any combination of letters, numbers, and underscores. it can be nested but must be unique.
Variable loop (usually an array) determines the number of times a variable is executed in a loop. for example, to output a variable in a section loop, brackets must be added to the variable to enclose the name variable.
For example:

The code is as follows:


<{Section name = data loop = $ myrow}>

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

<{/Section}> B. the php tag is used to directly embed a PHP script in the template, the tag format is "<{php}>" and "<{/php}> ".
C) the template of Smarty also supports if and else statements, and adds several features to adapt to the template engine. If and/if must appear in pairs; else and elseif can be used; the following conditional modifiers can be used: eq, ne, neq, gt, lt, lte, le, gte, ge, is even, is odd, is not even, is not odd, not, mod, p by, even by, odd by, == ,! =,>, <, <=,> =. When modifiers are used, they must be separated from variables or constants by spaces. Example:
<{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 and assign values to template variables
The data in the UI comes from the template variables defined in the PHP code. In PHP code, compile the PHP code, assign the value to be output to a template variable, and create a template page for output.
A) assign values to template variables through the custom function assign (). The first parameter is the name of the variable to be 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); // Use The assign method to write data in array $ array to myrow B) the template page is specified through the display method. Its syntax is as follows:
Void display (string template [, string cache_id [, string compile_id])
This method is used to specify the template page. The first required parameter specifies the type and path of a valid template resource. The first 2nd optional parameters specify a cache number; specify a compilation number for the 3rd optional parameters, and then compile a template into different versions. Key to the application of the display method The code is as follows:
$ Smarty-> display ("index. tpl"); // specify the template page to be output. 3. create a Session shopping cart.
The Session shopping cart is mainly implemented using Session variables. The so-called shopping cart is the two Session variables created through the session_register () function. goodsid stores the commodity ID and goodsnum stores the commodity quantity. The code for creating a Session shopping cart is as follows:

The code is as follows:


Session_start (); // initialize the session variable
Session_register ("goodsid"); // defines the session variable used to store the commodity ID
Session_register ("goodsnum"); // defines the session variable to store the quantity of purchased items.
?>


The session_register () function adds a Session variable throughout the domain. Syntax: boolean session_register (string name );
The parameter name is used to specify the name of the new Session variable.
4. use the array function to determine whether a specified item exists in the shopping cart.
To avoid repeated addition of items in the shopping cart, you need to judge the added items and the items stored in the shopping cart.
A) use the explode () function to convert the string stored in the goodsid variable to an array using the @ separator.
The explode () function returns an array composed of strings. each element is a substring separated by a separator as a boundary point.
Syntax: array explode (string separator, string, [ing limit])
Parameter description:
Separator: required, specifying where to split the string. Cannot be a null string; otherwise, explode () returns FALSE.
String: Required. the string to be split. Limit: (optional) specifies the maximum number of returned array elements. If the limit parameter is set, the returned array contains up to limit elements, and the last element contains the rest of the string. If the limit parameter is negative, all elements except the last-limit element are returned.

B) the in_array () function determines whether the specified item ID exists in the array. If yes, the item is already in the shopping cart; otherwise, the item does not exist, add the item ID to the shopping cart.

The in_inarray () function searches for the given value in the array. If yes, True is returned. otherwise, False is returned.
Syntax: bool in_array (mixed value, array [, bool type])
Parameter description:
Value: required, specifying the value to be searched in the array
Array: Required. specifies the array to be searched.
Type: Optional. if it is set to true, check whether the data to be searched is of the same type as the array.
In the shopping cart module, the code used to determine whether a specified item exists in the shopping cart is as follows:

The code is as follows:


Session_start (); // initialize the session variable
Session_register ("goodsid"); // defines the session variable used to store the commodity ID
Session_register ("goodsnum"); // defines the session variable to store the quantity of purchased items.
If ($ _ SESSION ["goodsid"] = "" & $ _ SESSION ["goodsnum"] = "") {// Determine whether the session variable is null
$ _ SESSION ["goodsid"] = $ _ GET ["id"]. "@"; // if the session variable is null, it is assigned the product ID and separated @.
$ _ SESSION ["goodsnum"] = "1 @"; // if the session variable is empty, the value is 1 and separated @.
} Else {// if the session variable is not empty
$ Array = explode ("@", $ _ SESSION ["goodsid"]); // writes data in the session variable to the array using the @ separator.
If (in_array ($ _ GET ["id"], $ array) {// if the specified ID exists in the array
Echo "script" alert ('The item has been placed in the shopping cart! '); History. back (); script ";
Exit;
}
// If the specified ID does not exist in the array, it indicates that the item has not been placed in the shopping cart.
$ _ SESSION ["goodsid"]. = $ _ GET ["id"]. "@"; // add this item to the shopping cart.
$ _ SESSION ["goodsnum"]. = "1 @"; // you can change the number of items.
}
Echo "script window. location. href = 'shopping _ car. php'; script";
?>


5. verify that the number of items entered is valid
In the preg_match () function, determine whether the value of the number of commodities to be submitted meets the standard of the regular expression. If yes, the value is valid. Otherwise, a prompt is displayed. The key code of the program is as follows:

The code is as follows:


$ Id = $ _ POST ["id"]; // obtain the product id
$ Num = $ _ POST ["goodsnum"]; // Obtain the number of items
$ Preg = "/^ [0-9] * [0-9] $ | ^ [0-9] * [0-9] $/"; // write a regular expression
If ($ num = "") {// determines whether the submitted value is null.
Echo "script" alert ('the number cannot be blank! '); History. back (); script ";
Exit;
} Else if (! Preg_match ($ preg, $ num, $ str) {// determines whether the submitted data is a positive integer.
Echo "script" alert ('the number can only be a positive integer! '); History. back (); script ";
Exit;
}


The preg_match () function searches the string for all content that matches the given regular expression. if so, True is returned. otherwise, False is returned. Syntax:
Syntax: int preg_match (string pattern, string sbuject [, array matches [, int flags])
Parameter description:
Pattern: Required parameter. the regular expression to be matched
Subject: required parameter. input string matches: optional parameter. An array of the output search results. for example, $ out [0] will contain results that match the entire pattern, $ out [1] will contain results matching the child pattern in the first captured bracket, and so on
Flags: an optional parameter marked with PREG_OFFSET_CAPTURE. the offset of a string that is attached to each matching result page is returned at the same time.

3. function implementation process
1. add product functions
The principle of adding a product is: first create a shopping cart, and then use the product ID ($ _ GET [id]) transmitted by the "buy" link on the product display page as the basis, add item (item ID) to the shopping cart and do not allow repeated addition. The by_commodity.php file is used to add items to the shopping cart.
First, create a shopping cart.
Then, judge whether the shopping cart is empty. if it is empty, add the item ID and quantity to the shopping cart. if it is not empty, you must determine whether the ID of the added item already exists in the shopping cart. If yes, you cannot add it again. otherwise, add the item ID to the shopping cart.
The code for adding a commodity program is as follows:

The code is as follows:


Header ("Content-type: text/html; charset = utf-8 ");
Session_start (); // initialize the session variable
Session_register ("goodsid"); // defines the session variable used to store the commodity ID
Session_register ("goodsnum"); // defines the session variable to store the quantity of purchased items.
If ($ _ SESSION ["goodsid"] = "" & $ _ SESSION ["goodsnum"] = "") {// Determine whether the session variable is null
$ _ SESSION ["goodsid"] = $ _ GET ["id"]. "@"; // if the session variable is null, it is assigned the product ID and separated @.
$ _ SESSION ["goodsnum"] = "1 @"; // if the session variable is empty, the value is 1 and separated @.
} Else {// if the session variable is not empty
$ Array = explode ("@", $ _ SESSION ["goodsid"]); // writes data in the session variable to the array using the @ separator.
If (in_array ($ _ GET ["id"], $ array) {// if the specified ID exists in the array
Echo "script" alert ('The item has been placed in the shopping cart! '); History. back (); script ";
Exit;
}
// If the specified ID does not exist in the array, it indicates that the item has not been placed in the shopping cart.
$ _ SESSION ["goodsid"]. = $ _ GET ["id"]. "@"; // add this item to the shopping cart.
$ _ SESSION ["goodsnum"]. = "1 @"; // you can change the number of items.
}
Echo "script window. location. href = 'shopping _ car. php'; script";
?>


2. implement the function of deleting items in the shopping cart
The delete operation is performed based on the item ID ($ _ GET [id]) passed in the "delete item" hyperlink. In the delete_commodity.php file, delete the item in the shopping cart based on the value passed by $ _ GET [id.
First, GET the value passed by $ _ GET [id. Then, The explode () function is applied to write the product ID and quantity data stored in the Session variable to the array and use @ as the separator.
Then, the array_search () function is applied to obtain the key name of the specified ID item in the array, and the value is null based on the value specified in the retrieved key name array.
Finally, the empty data in the array is written into the shopping cart to delete the specified item in the shopping cart.

The code is as follows:


Session_start (); // initialize the session variable
Require ("config. php"); // connect to the smarty Template
$ Id = $ _ GET ["id"]; // obtain the ID of the item to be deleted
$ Arrayid = explode ("@", $ _ SESSION ["goodsid"]); // converts the string of the product ID stored in the shopping cart to an array.
$ Arraynum = explode ("@", $ _ SESSION ["goodsnum"]); // converts the string of the number of items stored in the cart to an array.
$ Key = array_search ($ id, $ arrayid); // Obtain the specified data in the array and return the key name.
$ Arrayid [$ key] = ""; // assign a null value to the data in the array based on the returned key name
$ Arraynum [$ key] = ""; // assign a null value to the data in the array based on the returned key name
$ _ SESSION ["goodsid"] = implode ("@", $ arrayid); // add the data in the array to the shopping cart.
$ _ SESSION ["goodsnum"] = implode ("@", $ arraynum); // add the data in the array to the shopping cart.
Echo "script window. location. href = 'shopping _ car. php'; script";
$ Smarty-> display ("shopping_car.tpl ");
?>


The value of $ _ SESSION ["goodsid"] before deletion is "3 @ 2 @ 5 @", after $ id = 5 is deleted, the value of $ _ SESSION ["goodsid"] is "3 @ 2 @". In this way, excessive data @ exists in the Session @.
Solution:

The code is as follows:


Session_register ("goods"); // creates a session array.
$ Id = $ _ GET ['id'];
$ Arraygoods =$ _ SESSION ["goods"];
If ($ _ SESSION ["goods"] = ""){
$ _ SESSION ["goods"] [$ id] = "$ id, 1"; // Save the product based on the product ID. the key name is $ id and the key value is $ id, 1 (item ID and quantity of purchased items. the default quantity is 1)
} Else {
If (array_key_exists ($ id, $ _ SESSION ["goods"]) {
Echo "script" alert ('The item has been placed in the shopping cart! '); History. back (); script ";
Exit;
}
$ _ SESSION ["goods"] [$ id] = "$ id, 1 ";
}
?>


Product information is saved as an array, [4] => 4. The key name is the item ID, the value is the key name and the number of purchased items. To add or delete a product, you only need to find the corresponding product modification information based on the ID number.

The code is as follows:


Array
(
[4] => 4, 4
[3] => 3, 5
[1] => 1, 10
[2] => 2, 1
)


3. implementation of the order generation function
The order generation function is to read the filled order information from the database and reintegrate its content to form an order mode, and implement the order printing and order preview functions. The order generation operation is completed through two files. one is to read data from the database, assign the required data to the specified Smarty template variable, and specify the template page.

The code is as follows:


Session_start ();
Header ("Content-type: text/html; charset = utf-8 ");
Require_once ("conn. php ");
Require_once ("config. php ");
$ Array = array (); // defines 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); // write the obtained array value to the new array.
$ Smarty-> assign ("info", $ array );
$ Array = explode ("@", $ info ["spc"]);
$ Arraynum = explode ("@", $ info ["slc"]);
$ Totalprice = 0; // defines the price variable
$ 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); // read data from the database
$ Totalprices = $ infocart ["tb_commodity_price"] * $ arraynum ["$ I"]; // calculates the total price
Array_push ($ infocart, $ arraynum ["$ I"]); // write the purchased amount of data to the array returned by the database
Array_push ($ infocart, $ totalprices); // write the purchased amount of data to the array returned by the database
Array_push ($ arrayinfo, $ infocart); // Press the sorted data into the new array.
$ Totalprice + = $ infocart ["tb_commodity_price"] * $ arraynum ["$ I"]; // calculates the total price
}
}
Session_unregister ("goods ");
If (count ($ arrayinfo)> 0) {// checks 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 variables and generates an order.

4. download source code: Click to download

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.