php实现购物车功能(上)

2019-12-13 13:11:54于海丽

5.2 output_fns.php文件中的函数display_cart()

 

function display_cart($cart,$change = true,$images = 1) //显示购物车 
 { 
 echo "<table border="0" width="100%" cellspacing="0"> 
  <form action="show_cart.php" method="post"> 
   <tr> 
   <th colspan="". (1 + $images) ."" bgcolor=" #cccccc">Item</th> 
   <th bgcolor="#cccccc">Price</th> 
   <th bgcolor="#cccccc">Quantity</th> 
   <th bgcolor="#cccccc">Total</th> 
   </tr>"; 
 //输出购物车中每一项 
 foreach($cart as $isbn => $qty) 
 { 
  $book = get_book_details($isbn); 
  echo "<tr>"; 
  if($images == true) 
  { 
  echo "<td align="left">"; 
  if(file_exists("images/". $isbn .".jpg")) 
  { 
   $size = getimagesize("images/". $isbn .".jpg"); 
   if(($size[0] > 0) && ($size[1] > 1)) //图片长宽 
   { 
   echo "<img src="images/". $isbn .".jpg" 
    style="border: 1px solid black" 
    width="". ($size[0] / 3) ."" 
    height="". ($size[1] / 3) .""/>"; 
   } 
  } 
  else 
   echo " "; 
  echo "</td>"; 
  } 
  echo "<td align="left"> 
   <a href="show_book.php?isbn=". $isbn ."">". $book['title'] ."</a> by". $book['author'] ."</td> 
   <td align="center">$". number_format($book['price'],2) ."</td><td align="center">"; 
  
  //如果允许更改数量 
  if ($change == true) 
  { 
  echo "<input type="text" name="".$isbn."" value="".$qty."" size="3">"; 
  } 
  else 
  { 
  echo $qty; 
  } 
  echo "</td><td align="center">$".number_format($book['price']*$qty,2)."</td></tr>
"; 
 } 
 
  
 //总数 
 echo "<tr> 
  <th colspan="". (2 + $images) ."" bgcolor = "#cccccc"> </th> 
  <th align = "center" bgcolor="#cccccc">". $_SESSION['items'] ."</th> 
  <th align = "center" bgcolor="#cccccc">$". number_format($_SESSION['total_price'],2) ."</th></tr>"; 
  
 //保存按钮 
 if($change == true) 
 { 
  echo "<tr> 
   <td colspan = "". (2 + $images) .""> </td> 
   <td align = "center "> 
   <input type="hidden" name="save"value="true" /> 
   <input type = "image" src = "images/save-changes.gif" border = " 0 " alt = " Save Changes " /> 
   </td> 
   <td> </td> 
   </tr>"; 
 } 
 echo "</form></table>"; 
 } 

5.3 book_fns.php文件中的函数calculate_price()

function calculate_price($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; 
 } 

								 
			 
相关文章 大家在看