/ * Define the absolute path of the server */
define('BASE_PATH','E:PHPservices\');
/* Define the path of the Smarty directory */
define('SMARTY_PATH','SourceCode12
<{section name=data loop=$myrow }>
<{$ myrow[data].tb_commodity_name}> |
<{$myrow[data].tb_commodity_price}> |
< ;/tr>
<{/section}>b) The function of the php tag is to embed PHP scripts directly in the template. The format of the tag is "<{php}>" and "<{/php }>".
c) Smarty templates also support if and else statements, and several features have been added to adapt to the template engine. if and /if must appear in pairs; else and elseif clauses 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, div by, even by, odd by, ===, !=, >, <, <=, >=. When using modifiers, they must be separated from variables or constants by spaces. An example is as follows:
<{if $isShow=="F" }>
;Sorry, there is no product information in your shopping cart!
|
<{else}>
<{section name=data loop=$myrow }>
< tr>
<{$myrow[data].tb_commodity_name}> | <{$myrow[data].tb_commodity_price}> | < ;/tr>
<{/section}>
<{/if}>
(2) Define template variables in PHP code, as Template variable assignment
The data in the UI comes from the template variables defined in the PHP code. In the PHP code, complete the writing of the PHP code, assign the value to be output to a template variable, and finally formulate a template page for output.
a) Assigning values to template variables is completed through the custom function assign(), where 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); //Write the data in the array $array to myrow through the assign method b) Template page The specification is done through the display method, whose syntax is as follows:
void display(string template[,string cache_id[,string compile_id]])
This method is used to specify the template page, in which the first required parameter is It specifies the type and path of a legal template resource; the second optional parameter specifies a cache number; the third optional parameter specifies a compilation number, which is used when compiling a template into different versions. The key
code for the application of the display method is as follows:
$smarty->display("index.tpl"); //Specify template page 3 to be output, creation of Session shopping cart
Session The shopping cart is mainly implemented using Session variables. The so-called shopping cart is two Session variables created through the session_register() function; goodsid stores the ID of the product, and goodsnum stores the quantity of the product. The code for creating the Session shopping cart is as follows:
Copy the code The code is as follows:
session_start() ; //Initialize the session variable
session_register("goodsid"); //Define the session variable to store the product ID
session_register("goodsnum"); //Define the session variable to store the quantity of purchased goods
?>
The session_register() function adds a Session variable within the entire 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 the specified product exists in the shopping cart
In order to avoid repeated addition of products in the shopping cart, it is necessary to judge the added products and the products stored in the shopping cart. .
a) Apply the explode() function to convert the string stored in the goodsid variable into an array with @ as the delimiter.
The explode() function returns an array composed of strings, each element of which is a substring separated by the separator as a boundary point.
Syntax: array explode(string separator,string string,[ing limit])
Parameter description:
separator: required, specifies where to split the string . It cannot be an empty string, otherwise explode() returns FALSE
string: required, the string to be split. limit: optional, specifies 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 parameter is negative, all but the last -limit elements are returned.
b) The in_array() function determines whether the specified product ID exists in the array. If it exists, the product is already in the shopping cart; otherwise, the product does not exist, and the product ID is added to the shopping cart.
The in_inarray() function searches an array for a given value. Returns True if found, False otherwise.
Syntax: bool in_array(mixed value,array array[,bool type])
Parameter description:
value: required, specified to search in the array The value of
array: required, specifies the array to be searched.
type: Optional, if set to true, check whether the type of the searched data and the array are the same.
In the shopping cart module, the code to determine whether the specified product exists in the shopping cart is as follows:
Copy the code The code is as follows:
session_start(); //Initialize session variable
session_register("goodsid"); //Define session variable to store product ID
session_register("goodsnum"); //Define session variables to store the quantity of purchased goods
if($_SESSION["goodsid"]=="" && $_SESSION["goodsnum"]==""){ //Determine whether the session variable is empty
$_SESSION["goodsid"]=$_GET["id"]."@"; //If the session variable is empty, assign it the ID of the product and separate it with @
$_SESSION[ "goodsnum"]="1@"; //If the session variable is empty, assign it a value of 1 and separate it with @
}else{ //If the session variable is not empty
$array=explode ("@",$_SESSION["goodsid"]); //Use @ as the delimiter to write the data in the session variable into the array
if(in_array($_GET["id"],$ array)){ //If the specified ID exists in the reading array
echo "<script>alert('This product has been put into the shopping cart!');history.back();</script> ";
exit;
}
//If the specified ID does not exist in the array, it means that the product has not been placed in the shopping cart.
$_SESSION["goodsid"].=$_GET ["id"]."@"; //Add the product to the shopping cart
$_SESSION["goodsnum"].="1@"; //Change the quantity of the product
}
echo "<script>window.location.href='shopping_car.php';</script>";
?>
5, verify whether the quantity value of the input product is Valid
In the preg_match() function, it is judged whether the value of the submitted product quantity meets the standard of the regular expression. If it meets the standard, it is valid. Otherwise, a prompt message will be given. The key code of the program is as follows:
Copy code The code is as follows:
$id=$_POST["id"]; Get product id
$num=$_POST["goodsnum"]; //Get product quantity
$preg="/^[0-9]*[0-9]$|^[0-9] *[0-9]$/"; //Write regular expression
if($num==""){ The quantity cannot be empty!');history.back();";
exit;
}else if(!preg_match($preg,$num,$str)){ //Judge Whether the submitted data is a positive integer
echo "<script>alert('The number can only be a positive integer!'); history.back();</script>";
exit;
}
preg_match() function, searches for all content matching the given regular expression in the string, returns True if it exists, otherwise returns False. The syntax is as follows:
Syntax: int preg_match(string pattern, string sbuject[,array matches[,int flags]])
Parameter description:
pattern: Necessary parameters, the regular expression that needs to be matched
subject: necessary parameters, the input string matches: optional parameters. An array of output search results, for example $out[0] will contain results that match the entire pattern, $out[1] will contain results that match the first captured subpattern in parentheses, and so on
flags: Optional parameter, mark: PREG_OFFSET_CAPTURE, for each matching result page that appears, return the attached string offset
3. Function implementation process
1. Add product function
The implementation principle of adding product function is: first create a shopping cart, and then use the product display page Add the product (product ID) to the shopping cart based on the product ID ($_GET[id]) passed by the "Purchase" link in the shopping cart, and repeated additions are not allowed. Adding 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, add the ID and quantity of the product to the shopping cart; if it is not empty, determine whether the ID of the added product already exists in the shopping cart. If it exists, it cannot be added repeatedly, otherwise the product ID will be added to the shopping cart.
Add the product program code as follows:
Copy the code The code is as follows:
header( "Content-type:text/html;charset= utf-8");
session_start(); //Initialize session variable
session_register("goodsid"); //Define session variable to store product ID
session_register("goodsnum"); //Define session variables to store the quantity of purchased goods
if($_SESSION["goodsid"]=="" && $_SESSION["goodsnum"]=="") { //Determine whether the session variable is empty
$_SESSION["goodsid"]=$_GET["id"]."@"; //If the session variable is empty, assign it the ID of the product, and Separated by @
$_SESSION["goodsnum"]="1@"; //If the session variable is empty, assign it a value of 1 and separated by @
}else{ //If the session variable is not Is empty
$array=explode("@",$_SESSION["goodsid"]); //Use @ as the separator to write the data in the session variable into the array
if(in_array( $_GET["id"],$array)){ //If the specified ID exists in the reading array
echo "<script>alert('This product has been put into the shopping cart!');history. back();</script>";
exit;
}
//If the specified ID does not exist in the array, it means that the product has not been placed in the shopping cart
$_SESSION ["goodsid"].=$_GET["id"]."@"; //Add the product to the shopping cart
$_SESSION["goodsnum"].="1@"; //Change the product Quantity
}
echo "<script>window.location.href='shopping_car.php';</script>";
?>
2. Implementation of the function of deleting items in the shopping cart
The operation of deleting items in the shopping cart is performed based on the product ID ($_GET[id]) passed in the "Delete this item" hyperlink. In the delete_commodity.php file, delete the items in the shopping cart based on the value passed by $_GET[id].
First, get the value passed by $_GET[id]. Then, use the explode() function to write the product ID and quantity data stored in the Session variable into the array, using @ as the separator.
Next, use the array_search() function to obtain the key name of the specified ID product in the array, and assign the specified data in the array to empty based on the obtained key name.
Finally, write the reassigned empty data in the array into the shopping cart, thereby completing the deletion of the specified item in the shopping cart.
Copy code The code is as follows:
session_start(); //Initialize session variables
require("config.php"); //Connect smarty template
$id=$_GET["id "]; //Get the ID of the product to be deleted
$arrayid=explode("@",$_SESSION["goodsid"]); //Convert the string of product ID stored in the shopping cart into an array
$arraynum=explode("@",$_SESSION["goodsnum"]); //Convert the string of the number of goods stored in the shopping cart into an array
$key=array_search($id,$arrayid ); //Get the specified data in the array and return the key name
$arrayid[$key]=""; //Assign the data in the array to empty based on the returned key name
$arraynum [$key]=""; //Assign the data in the array to empty based on the returned key name
$_SESSION["goodsid"]=implode("@",$arrayid); //Re-assign the array Add the data in the shopping cart to the shopping cart
$_SESSION["goodsnum"]=implode("@",$arraynum); //Re-add the data in the array to the shopping cart
echo "";
exit;
}
$_SESSION["goods"][$ id]="$id,1";
}
?>
Product information is saved in the form of an array, [4] => 4,4. The key name is the product ID, and the value is the key name and the quantity of the purchased product. To add or delete products, you only need to find the corresponding product modification information based on the ID number.
Copy code 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, re-integrate its contents to form an order model, and realize the functions of order printing and order preview. . 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.
Copy code 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(); //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); //Write the obtained array value into a new array
$smarty->assign("info",$array);
$array= explode("@",$info["spc"]);
$arraynum=explode("@",$info["slc"]);
$totalprice=0; //Define price variables
$arrayinfo=array(); //Create 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 the data in the database
$totalprices=$infocart["tb_commodity_price"]*$arraynum["$i"]; //Calculate the total price
array_push($infocart,$arraynum["$i" ]); //Write the purchase quantity data into the array returned from the database.
array_push($infocart,$totalprices); //Write the purchase quantity data into the array returned from the database.
array_push($arrayinfo,$infocart); //Push the sorted data into the new array created
$totalprice+=$infocart["tb_commodity_price"]*$arraynum["$i"]; //Calculate the total price
}
}
session_unregister("goods");
if(count($arrayinfo)>0){ $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 template variables The data stored in it generates an order.
4. Source code download: Click to download
http://www.bkjia.com/PHPjc/327863.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327863.htmlTechArticle1. Shopping Cart Overview The shopping cart provides a place for consumers to temporarily store goods during online shopping. Its main functions include: adding products, deleting products, changing product quantity, sales...