1 <?php
2 /**
3 * 根据Cookie值对购物车商品数量和总价格调用
4 */
5 require("class/connect.php");
6
7 $totalProducts = 0; //购物车商品总数
8 $totalPrice = 0.0; //购物车商品总价
9
10 // |77,243|2!|77,237|3!
11 $cookieString = explode("!",$_COOKIE['zeuqcmybuycar']);
12
13 try{
14 //遍历商品
15 for($i = 0; $i < count($cookieString)-1; $i++){
16 $priceAndNumber = explode("|",$cookieString[$i]);
17 $thisNum = $priceAndNumber[2]; //当前商品的数量
18 $thisId = explode(",",$priceAndNumber[1]);
19 $thisId = $thisId[1]; //当前商品的ID
20 $thisPrice = this_price($thisId); //当前商品价格
21
22 $totalPrice += $thisPrice * $thisNum; //购物车商品总价累加
23 $totalProducts += $thisNum; //购物车商品总数累加
24 }
25
26 echo "document.write(\"".displayResultJs($totalPrice,$totalProducts)."\")"; //显示结果Js形式输出
27
28 }catch (Exception $e){
29 echo $e->getMessage();
30 }
31
32
33 /**计算商品价格*/
34 function this_price($id){
35 $connect = connectDB();
36 $query = "select price from phome_ecms_news where id = ".$id;
37 if(!$connect){
38 throw new Exception("数据库链接不成功,请检查!");
39 }
40 if(!$result = $connect -> query($query)){
41 throw new Exception("查询失败!");
42 }
43 $row = $result -> fetch_assoc();
44
45 return $row['price'];
46 }
47
48 /**链接数据库*/
49 function connectDB(){
50 global $phome_db_server,$phome_db_username,$phome_db_password,$phome_db_dbname,$phome_db_char;
51 $connect = new mysqli($phome_db_server,$phome_db_username,$phome_db_password,$phome_db_dbname);
52 $connect -> query("set Names ".$phome_db_char);
53 return $connect;
54 }
55
56 /**显示结果Js*/
57 function displayResultJs($totalPrice,$totalProducts){
58 return "<div class='car'>您的购物车中有 {$totalProducts} 件商品,总计金额 ¥{$totalPrice}元。<br />点击查看 <a href='/e/ShopSys/buycar/'>结算&gt;&gt;</a> </div>";
59 }
60 ?>

原文链接:https://www.cnblogs.com/allenxusc/archive/2012/03/31/2427474.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注