28.5.3 将物品添加到购物车
如果用户点击"Add to Cart"按钮进入show_cart.php页面,在显示其购物车内容之前,我们要做一些工作。特别地,需要将适当的物品添加到购物车中,如下所示。
首先,如果该用户此前没有在购物车中添加任何物品,那么该用户没有一个购物车,需要为其创建一个购物车:
if(!isset($_SESSION['cart'])){
$_SESSION['cart']=array();
$_SESSION['items']=0;
$_SESSION['total_price']='0.00';
}
初始状态下,购物车是空的。
其次,建立了一个购物车后,可以将物品添加到购物车内:
if(isset($_SESSION['cart'][$new])){
$_SESSION['cart'][$new]++;
}else{
$_SESSION['cart'][$new]=1;
}
在这里,我们检查了该物品是否已经在购物车中存在,如果是,我们将该物品的数量增1,否则,添加新物品到购物车。
再次,我们必须计算购物车中所有物品的总价格和数量。要完成这些操作,我们使用了calculate_price()函数和calculate_items()函数,如下所示:
$_SESSION['total_price']=calculate_price($_SESSION['cart']);
$_SESSION['items']=calculate_items($_SESSION['cart']);
这些函数位于book_fns.php函数库中。其代码如程序清单28-11和程序清单28-12所示。
程序清单28-11 book_fns.php文件中的calculate_price()函数——计算和返回购物车中物品的总价格
function calculate_price($cart){
//sum total price for all items in shopping cart
$price=0.0;
if(is_array($cart)){
$conn=db_connect();
foreach($cart as$isbn=>$qty){
$query="select price from books where isbn='".$isbn."'";
$result=$conn->query($query);
if($result){
$item=$result->fetch_object();
$item_price=$item->price;
$price+=$item_price*$qty;
}
}
}
return$price;
}
可以看到,calculate_price()函数工作的时候查询了数据库中每个物品的价格。该操作可能会有些慢,因此如果没有必要,应该避免这样的计算。我们将保存此价格(还有物品总数)到会话变量中,当购物车改变的时候才重新计算。
程序清单28-12 book_fns.php文件中的calculate_items()函数——该函数计算并返回购物车中物品的总数
function calculate_items($cart){
//sum total items in shopping cart
$items=0;
if(is_array($cart)){
foreach($cart as$isbn=>$qty){
$items+=$qty;
}
}
return$items;
}
calculate_items()函数相当简单;它只是扫描了购物车,使用array_sum()函数将每个物品的数量加起来得到总物品数量。如果还没有数组(或者购物车为空),它将返回0。