《PHP和MySQL Web开发》精彩的地方收录

1、用SESSION来做的购物车,做成数组,用isbn对应书的数量作为二维数组保存

  $new GET传值加入购物车,submit是修改数量,提交后的表单,通过历遍原来的数组,对应isbn修改最新的数量

   对数组的运用很巧妙。收藏下来

 1   if ($new) {
 2       if (!isset($_SESSION['cart'])) {
 3       $_SESSION['cart'] = array();
 4       $_SESSION['items'] = 0;
 5       $_SESSION['total_price'] = '0.00';
 6     }
 7 
 8     if (isset($_SESSION['cart'][$new])) {
 9       $_SESSION['cart'][$new]++;
10     }else{
11       $_SESSION['cart'][$new] = 1;
12     }
13 
14     $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
15     $_SESSION['items'] = calculate_items($_SESSION['cart']);
16   }
17 
18   if ($_POST['submit']) {
19     foreach ($_SESSION['cart'] as $isbn => $qty) {
20     if ($_POST[$isbn] == '0') {
21       unset($_SESSION['cart'][$isbn]);
22     }else{
23       $_SESSION['cart'][$isbn] = $_POST[$isbn];
24     }
25     }
26     $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
27     $_SESSION['items'] = calculate_items($_SESSION['cart']);
28   }
29 
30 //计算购物车里商品总价
31    function calculate_price($cart){
32     $db = db_connect();
33     $total_prices = 0.00;
34     foreach ($cart as $isbn => $qty) {
35       $query = "select price from books where isbn = '".$isbn."'";
36       $result = $db->query($query);
37       $price = $result->fetch_assoc();
38       $prices = $price['price'] * $qty;
39       $total_prices += $prices;
40     }
41     return $total_prices;
42    }
43 
44 //计算购物车里商品总数量
45    function calculate_items($cart){
46     $db = db_connect();
47     $total_qty = 0;
48     foreach ($cart as $isbn => $qty) {
49       $total_qty += $qty;
50     }
51     return $total_qty;
52    }

 

2、number_format()  函数 — 以千位分隔符方式格式化一个数字(我挺喜欢这个,价格看的清楚

    如果只提供第一个参数,number的小数部分会被去掉 并且每个千位分隔符都是英文小写逗号","

    如果提供两个参数,number将保留小数点后的位数到你设定的值,其余同楼上

    如果提供了四个参数,number 将保留decimals个长度的小数部分, 小数点被替换为dec_point,千位分隔符替换为thousands_sep

    如果不习惯千位用逗号分隔的,可以下面这样

    $chinese_format_number = number_format($number, 2, '.', '');   // 1234.57

 

3、MySQL事务,有很多数据库操作的时候,为了保持数据一致,需要全部执行通过才会执行

   $db->autocommit(false);  开始,关闭自动提交模式

   $db->commit();结束,统一提交

   $db->autocommit(true); 开启自动提交模式

    

posted @ 2015-09-15 14:55  luwenjie  阅读(133)  评论(0编辑  收藏  举报