首頁 後端開發 php教程 php实现购物车功能(上)_php技巧

php实现购物车功能(上)_php技巧

May 16, 2016 pm 08:00 PM
php 購物車

本文分两篇为大家介绍php实现购物车功能,具有一定的参考价值,相信大家一定喜欢。

1、需求分析

 我们需要找到一种将数据库连接到用户的浏览器的方法。用户能够按目录浏览商品。 用户应该能够从商品目录中选取商品以便此后的购买。我们也要能够记录他们选中的物品。 当用户完成购买,要合计他们的订单,获取运送商品细节,并处理付款。 创建一个管理界面,以便管理员在上面添加、编辑图书和目录。

2、解决方案

2.1 用户视图



2.2 管理员视图


2.3 Book-O-Rama中的文件列表

3、实现数据库3.1 创建book_sc数据库的SQL代码

CREATE DATABASE book_sc; #创建book_sc数据库 
 
USE book_sc; #使用book_sc数据库 
 
CREATE TABLE customers #创建用户表 
( 
 customerid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 name CHAR(60) NOT NULL, 
 address CHAR(80) NOT NULL, 
 city CHAR(30) NOT NULL, 
 state CHAR(10), 
 zip CHAR(10), 
 country CHAR(20) NOT NULL 
); 
 
CREATE TABLE orders #创建订单表 
( 
 orderid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 customerid INT UNSIGNED NOT NULL, 
 amount FLOAT(6,2), 
 date DATE NOT NULL, 
 order_status CHAR(10), 
 ship_name CHAR(60) NOT NULL, 
 ship_address CHAR(80) NOT NULL, 
 ship_city CHAR(30) NOT NULL, 
 ship_state CHAR(20), 
 ship_zip CHAR(10), 
 ship_country CHAR(20) NOT NULL 
); 
 
CREATE TABLE books #创建图书表 
( 
 isbn CHAR(13) NOT NULL PRIMARY KEY, 
 author CHAR(80), 
 title CHAR(100), 
 catid INT UNSIGNED, 
 price FLOAT(4,2) NOT NULL, 
 description VARCHAR(255) 
); 
 
CREATE TABLE categories #创建目录表 
( 
 catid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 catname CHAR(60) NOT NULL 
); 
 
CREATE TABLE order_items #订单物品表 
( 
 orderid INT UNSIGNED NOT NULL, 
 isbn CHAR(13) NOT NULL, 
 item_price FLOAT(4,2) NOT NULL, 
 quantity TINYINT UNSIGNED NOT NULL, 
 PRIMARY KEY(orderid,isbn) 
); 
 
CREATE TABLE admin #管理员表 
( 
 username char(16) NOT NULL PRIMARY KEY, 
 password CHAR(40) NOT NULL 
); 
 
GRANT SELECT,INSERT,UPDATE,DELETE 
on book_sc.* 
to book_sc@localhost IDENTIFIED by 'password'; 
登入後複製

3.2 数据库测试数据文档

USE book_sc; 
 
 
INSERT INTO books VALUES ('0672329166','Luke Welling and Laura Thomson','PHP and MySQL Web Development',1,49.99, 
'PHP & MySQL Web Development teaches the reader to develop dynamic, secure e-commerce web sites. You will learn to integrate and implement these technologies by following real-world examples and working sample projects.'); 
INSERT INTO books VALUES ('067232976X','Julie Meloni','Sams Teach Yourself PHP, MySQL and Apache All-in-One',1,34.99, 
'Using a straightforward, step-by-step approach, each lesson in this book builds on the previous ones, enabling you to learn the essentials of PHP scripting, MySQL databases, and the Apache web server from the ground up.'); 
INSERT INTO books VALUES ('0672319241','Sterling Hughes and Andrei Zmievski','PHP Developer\'s Cookbook',1,39.99, 
'Provides a complete, solutions-oriented guide to the challenges most often faced by PHP developers\r\nWritten specifically for experienced Web developers, the book offers real-world solutions to real-world needs\r\n'); 
 
INSERT INTO categories VALUES (1,'Internet'); 
INSERT INTO categories VALUES (2,'Self-help'); 
INSERT INTO categories VALUES (5,'Fiction'); 
INSERT INTO categories VALUES (4,'Gardening'); 
 
INSERT INTO admin VALUES ('admin', sha1('admin')); 
登入後複製

4、实现在线目录


主页-目录
由以下代码实现:
4.1 index.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 网站首页,显示系统中的图书目录 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); //开始会话 
 do_html_header('Welcome to Book-O-Rama'); //页头 
 
 echo "<p>Please choose a category:</p>"; 
 
 $cat_array = get_categories(); //从数据库获取目录 
 
 display_categories($cat_array); //显示目录链接 
 
 if(isset($_SESSION['admin_user'])) //如果是管理员,显示管理员操作 
 display_button("admin.php","admin-menu","Admin Menu"); 
 do_html_footer(); //页尾 
&#63;> 

登入後複製

4.2 book_fns.php文件中的函数get_categories()

function get_categories() //从数据库中获取目录列表 
 { 
 $conn = db_connect(); //连接数据库 
 $query = "select catid,catname from categories"; 
 $result = @$conn ->query($query); 
 if(!$result) //查询失败,返回false 
  return false; 
 $num_cats = @$result ->num_rows; 
 if($num_cats == 0) //数据库中无目录,返回false 
  return false; 
 $result = db_result_to_array($result); 
 return $result; 
 } 

登入後複製

4.3 output_fns.php文件中的函数display_categories()

function display_categories($cat_array) //输出目录 
 { 
 if(!is_array($cat_array)) 
 { 
  echo "<p>No categories currently available</p>"; 
  return; 
 } 
 echo "<ul>"; 
 foreach($cat_array as $row) 
 { 
  $url = "show_cat.php&#63;catid=". $row['catid']; 
  $title = $row['catname']; 
  echo "<li>"; 
  do_html_URL($url,$title); 
  echo "</li>"; 
 } 
 echo "</ul>"; 
 echo "<hr/>"; 
 } 

登入後複製

4.4 db_fns.php文件中的函数db_result_to_array()

function db_result_to_array($result) //结果到数组 
 { 
 $res_array = array(); 
  
 for($count = 0; $row = $result ->fetch_assoc(); $count++) 
  $res_array[$count] = $row; 
  
 return $res_array; 
 } 

登入後複製


Internet目录下的所有图书

由以下代码实现:

4.5 show_cat.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 显示特定目录包含的所有图书 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 @$catid = $_GET['catid']; 
 $name = get_category_name($catid); 
 
 do_html_header($name); 
 
 $book_array = get_books($catid); 
 
 display_books($book_array); 
 
 //如果是管理员,显示管理界面按钮 
 if(isset($_SESSION['admin_user'])) 
 { 
 display_button("index.php","continue","Continue Shopping"); 
 display_button("admin.php","admin-menu","Admin Menu"); 
 display_button("edit_category_form.php&#63;catid=". $catid,"edit-category","Edit Category"); 
 } 
 else //否则显示主界面按钮 
 { 
 display_button("index.php","continue-shopping","Continue Shopping"); 
 } 
 do_html_footer(); 
&#63;> 
登入後複製

4.6 book_fns.php文件中的函数get_category_name()

function get_category_name($catid) //获取目录名 
 { 
 $conn = db_connect(); //连接数据库 
 $query = "select catname from categories where catid = '". $catid ."'"; 
 $result = @$conn ->query($query); 
 if(!$result) //查询失败,原因为查询出错 
  return false; 
  
 $num_cats = @$result ->num_rows; 
  
 if($num_cats == 0) //查询失败,原因为无目录 
  return false; 
 $row = $result ->fetch_object(); 
 return $row ->catname; 
 } 

登入後複製

4.8 book_fns.php文件中的函数get_books()

function get_books($catid) //从数据库中获取图书 
 { 
 if((!$catid) || ($catid == '')) //如果目录ID为空 
  return false; 
  
 $conn = db_connect(); 
 $query = "select * from books where catid = '". $catid ."'"; 
 $result = @$conn ->query($query); 
 if(!$result) //查询失败,原因为查询出错 
  return false; 
  
 $num_books = @$result ->num_rows; 
  
 if($num_books == 0) //查询失败,原因为无图书 
  return false; 
  
 $result = db_result_to_array($result); 
 return $result; 
 } 

登入後複製

4.9 output_fns文件中的函数display_books()

function display_books($book_array) //输出图书 
 { 
 if(!is_array($book_array)) 
  echo "<p>No books currently available in this category</p>"; 
 else //有图书,建表 
 { 
  echo "<table width = \"100%\" border=\"0\">"; 
  
  foreach($book_array as $row) 
  { 
  $url = "show_book.php&#63;isbn=". $row['isbn']; 
  echo "<tr><td>"; 
  // 如果图片存在 
  if(@file_exists("images/". $row['isbn'] .".jpg")) 
  { 
   $title = "<img  src="/static/imghw/default1.png"  data-src="http://files.jb51.net/file_images/article/201601/2016010516190814.png"  class="lazy"  src=\"images/". $row['isbn'] .".jpg\" style=\"border: 1px solid black\"/ alt="php实现购物车功能(上)_php技巧" >"; 
   do_html_URL($url,$title); 
  } 
  else 
   echo " "; 
   
  echo "</td><td>"; 
  $title = $row['title'] ." by ". $row['author']; 
  do_html_URL($url,$title); 
  echo "</td></tr>"; 
  } 
  echo "</table>"; 
 } 
 echo "<hr/>"; 
 } 
登入後複製


PHP and MySQL Web Development的详细信息

由以下代码实现:

4.10 show_book.php

<&#63;php 
 /** 
 * @author switch 
 * @copyright 2015 
 * 显示特定图书的详细信息 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 $isbn = $_GET['isbn']; 
 
 $book = get_book_details($isbn); 
 do_html_header($book['title']); 
 display_book_details($book); 
 
 //设置继续按钮 
 $target = "index.php"; 
 if($book['catid']) 
 $target = "show_cat.php&#63;catid = ". $book['catid']; 
 
 //如果是管理员,显示编辑链接 
 if(check_admin_user()) 
 { 
 display_button("edit_book_form.php&#63;isbn=". $isbn,"edit-item","Edit Item"); 
 display_button("admin.php","admin-menu","Admin Menu"); 
 display_button($target,"continue","Continue"); 
 } 
 else 
 { 
 display_button("show_cart.php&#63;new=". $isbn,"add-to-cart","Add". $book['title']." To My Shopping Cart"); 
 display_button($target,"continue-shopping","Continue Shopping"); 
 } 
 do_html_footer(); 
&#63;> 
登入後複製

4.11 book_fns.php文件中的函数get_book_details()

function get_book_details($isbn) //从数据库中获取一本图书的详细说明 
 { 
 if((!$isbn) || ($isbn == '')) //如果图书统一书号为空 
  return false; 
  
 $conn = db_connect(); //连接数据库 
 $query = "select * from books where isbn = '". $isbn ."'"; 
 $result = @$conn ->query($query); 
 if(!$result) //查询失败,原因为查询出错 
  return false; 
 $result = @$result ->fetch_assoc(); 
 return $result; 
 } 

登入後複製

4.12 output_fns.php文件中的函数display_book_details()

function display_book_details($book) //输出图书详细说明 
 { 
 if(is_array($book)) 
 { 
  echo "<table><tr>"; 
  // 如果图片存在 
  if(@file_exists("images/". $book['isbn'] .".jpg")) 
  { 
  $size = getimagesize("images/". $book['isbn'] .".jpg"); 
  if(($size[0] > 0) && ($size[1] > 0)) 
  { 
   echo "<td><img  src="/static/imghw/default1.png"  data-src="http://files.jb51.net/file_images/article/201601/2016010516190915.png"  class="lazy"  src=\"images/". $book['isbn'] .".jpg\" style=\"border: 1px solid black\"/ alt="php实现购物车功能(上)_php技巧" ></td>"; 
  } 
  } 
  echo "<td><ul>"; 
  echo "<li><strong>Author:</strong>"; 
  echo $book['author']; 
  echo "</li><li><strong>ISBN:</strong>"; 
  echo $book['isbn']; 
  echo "</li><li><strong>Our Price:</strong>"; 
  echo number_format($book['price'],2); 
  echo "</li><li><strong>Description:</strong>"; 
  echo $book['description']; 
  echo "</li></ul></td></tr></table>"; 
 } 
 else 
 { 
  echo "<p>The details of this book cannot be displayed at this time.</p>"; 
 } 
 echo "<hr/>"; 
 } 

登入後複製

5、实现购物车


不使用参数的脚本只显示购物车的内容


带有参数new的脚本将添加一个物品到购物车

由以下代码实现:
5.1 show_cart.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 显示用户购物车的内容。也用来向购物车添加图书 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 @$new = $_GET['new']; 
 
 if($new) 
 { 
 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; 
 } 
  
 $_SESSION['total_price'] = calculate_price($_SESSION['cart']); 
 $_SESSION['items'] = calculate_items($_SESSION['cart']); 
 } 
 
 if(isset($_POST['save'])) 
 { 
 foreach($_SESSION['cart'] as $isbn => $qty) 
 { 
  if($_POST[$isbn] == '0') 
  unset($_SESSION['cart'][$isbn]); 
  else 
  $_SESSION['cart'][$isbn] = $_POST[$isbn]; 
 } 
 
 $_SESSION['total_price'] = calculate_price($_SESSION['cart']); 
 $_SESSION['items'] = calculate_items($_SESSION['cart']); 
 } 
 
 do_html_header("Your shopping cart"); 
 
 if((@$_SESSION['cart']) && (array_count_values($_SESSION['cart']))) 
 { 
 display_cart($_SESSION['cart']); 
 } 
 else 
 { 
 echo "<p>There are no items in your cart</p><hr/>"; 
 } 
 
 $target = "index.php"; 
 
 //如果只有一种物品添加到购物车,可以继续购物 
 if($new) 
 { 
 $details = get_book_details($new); 
 if($details['catid']) 
 { 
  $target = "show_cat.php&#63;catid=". $details['catid']; 
 } 
 } 
 
 display_button($target,"continue-shopping","Continue Shopping"); 
 
 //SSL链接--需要配置,PS:没配置,所以不能使用 
// $path = $_SERVER['PHP_SELF']; //获取路径 
// $server = $_SERVER['SERVER_NAME']; //获取主机名 
// $path = str_replace('show_cart.php','',$path); 
// display_button("https://". $server . $path ."checkout.php","go-to-checkout","Go To Checkout"); 
 
 //非SSL链接 
 display_button("checkout.php","go-to-checkout","Go To Checkout"); 
 
 do_html_footer(); 
&#63;> 
登入後複製

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="/static/imghw/default1.png"  data-src="http://files.jb51.net/file_images/article/201601/2016010516190917.png"  class="lazy"  src=\"images/". $isbn .".jpg\" 
    style=\"border: 1px solid black\" 
     style="max-width:90%"". ($size[0] / 3) ."\" 
    height=\"". ($size[1] / 3) ."\"/>"; 
   } 
  } 
  else 
   echo " "; 
  echo "</td>"; 
  } 
  echo "<td align=\"left\"> 
   <a href=\"show_book.php&#63;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>\n"; 
 } 
 
  
 //总数 
 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; 
 } 

登入後複製

5.4 book_fns.php文件中的函数calculate_items()

function calculate_items($cart) //计算购物车中的物品总数 
 { 
 $items = 0; 
 if(is_array($cart)) 
 { 
  foreach($cart as $isbn => $qty) 
  $items += $qty; 
 } 
 return $items; 
 } 

登入後複製


获取顾客的详细信息

由以下代码实现:
5.5 checkout.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 向用户显示所有的订单细节。获取商品运送细节 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 do_html_header("Checkout"); 
 
 if((@$_SESSION['cart']) && (array_count_values($_SESSION['cart']))) 
 { 
 display_cart($_SESSION['cart'],false,0); 
 display_checkout_form(); 
 } 
 else 
 { 
 echo "<p>Thers are no items in your cart</p>"; 
 } 
 
 display_button("show_cart.php","continue-shopping","Continue Shopping"); 
 
 do_html_footer(); 
&#63;> 

登入後複製

5.6 output_fns.php文件中的display_checkout_form()

function display_checkout_form() //输出付款台界面 
 { 
 &#63;> 
  <br /> 
  <table border="0" width="100%" cellspacng="0"> 
  <form action="purchase.php" method="post"> 
   <tr> <!--客户信息--> 
   <th colspan="2" bgcolor="#cccccc">Your Details</th> 
   </tr> 
   <tr> 
   <td>Name</td> 
   <td><input type="text" name="name" value="" maxlength="40" size="40"/></td> 
   </tr> 
   <tr> 
   <td>Address</td> 
   <td><input type="text" name="address" value="" maxlength="40" size="40"/></td> 
   </tr> 
   <tr> 
   <td>City/Suburb</td> 
   <td><input type="text" name="city" value="" maxlength="20" size="40"/></td> 
   </tr> 
   <tr> 
   <td>State/Province</td> 
   <td><input type="text" name="state" value="" maxlength="20" size="40"/></td> 
   </tr> 
   <tr> 
   <td>Postal Code or Zip Code</td> 
   <td><input type="text" name="zip" value="" maxlength="10" size="40"/></td> 
   </tr> 
   <tr> 
   <td>Country</td> 
   <td><input type="text" name="country" value="" maxlength="10" size="40"/></td> 
   </tr> 
   
   <tr> <!--运单信息--> 
   <th colspan="2" bgcolor="#cccccc">Shipping Address(leave blank if as above)</th> 
   </tr> 
   <tr> 
   <td>Name</td> 
   <td><input type="text" name="ship_name" maxlength=""/></td> 
   </tr> 
   <tr> 
   <td>Address</td> 
   <td><input type="text" name="ship_address" value="" maxlength="40" size="40"/></td> 
   </tr> 
   <tr> 
   <td>City/Suburb</td> 
   <td><input type="text" name="ship_city" value="" maxlength="20" size="40"/></td> 
   </tr> 
   <tr> 
   <td>State/Province</td> 
   <td><input type="text" name="ship_state" value="" maxlength="20" size="40"/></td> 
   </tr> 
   <tr> 
   <td>Postal Code or Zip Code</td> 
   <td><input type="text" name="ship_zip" value="" maxlength="10" size="40"/></td> 
   </tr> 
   <tr> 
   <td>Country</td> 
   <td><input type="text" name="ship_country" value="" maxlength="20" size="40"/></td> 
   </tr> 
   <tr> 
   <td colspan="2" align="center"> 
    <p> 
    <strong>Please press Purchase to confirm your purchase, or Continue Shopping to add or remove items.</strong> 
    </p> 
    <&#63;php display_form_button("purchase","Purchase There Items"); &#63;> 
   </td> 
   </tr> 
  </form> 
  </table> 
  <hr /> 
 <&#63;php 
 } 
登入後複製


已填写好信息的订单


获取客户信用卡信息

由以下代码实现:
5.7 purchase.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 从用户获取付款细节 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 do_html_header("Checkout"); 
 
 //创建变量 
 $name = $_POST['name']; 
 $address = $_POST['address']; 
 $city = $_POST['city']; 
 $zip = $_POST['zip']; 
 $country = $_POST['country']; 
 
 //如果订单细节填满 
 if(($_SESSION['cart']) && ($name) && ($address) && ($city) && ($zip) && ($country)) 
 { 
 if(insert_order($_POST) != false) 
 { 
  display_cart($_SESSION['cart'],false,0); 
  
  display_shipping(calculate_shipping_cost()); 
  
  display_card_form($name); 
  
  display_button("show_cart.php","continue-shopping","Continue Shopping"); 
 } 
 else 
 { 
  echo "<p>Could not store data, please try again.</p><hr/>"; 
  display_button('checkout.php','back','Back'); 
 } 
 } 
 else 
 { 
 echo "<p>You did not fill in all the fields, please try again.</p><hr/>"; 
 display_button('checkout.php','back','Back'); 
 } 
 do_html_footer(); 
&#63;> 

登入後複製

5.8 order_fns.php文件中的函数insert_order()

function insert_order($order_details) //提取订单细节作为变量 
 { 
 extract($order_details); 
  
 //设置邮寄地址为当前地址 
 if((!$ship_name) && (!$ship_address) && (!$ship_city) && (!$ship_state) && (!$ship_zip) &&(!$ship_country)) 
 { 
  $ship_name = $name; 
  $ship_address = $address; 
  $ship_city = $city; 
  $ship_state = $state; 
  $ship_zip = $zip; 
  $ship_country = $country; 
 } 
  
 //连接数据库 
 $conn = db_connect(); 
  
 //事务开始,必须关闭自动提交 
 $conn ->autocommit(false); 
  
 $query = "select customrid from customers where 
   name ='". $name ."' and address = '". $address ."' 
   and city = '". $city ."' and state = '". $state ."' 
   and zip = '". $zip ."' and country = '". $country ."'"; 
   
 $result = $conn ->query($query); 
  
 if(@$result ->num_rows > 0) 
 { 
  $customer = $result ->fetch_object(); 
  $customerid = $customer ->customerid; 
 } 
 else 
 { 
  $query = "insert into customers values 
   ('','". $name ."','". $address ."','". $city ."','". $state ."','". $zip ."','". $country ."')"; 
  $result = $conn ->query($query); 
  
  if(!$result) 
  return false; 
 } 
  
 $customerid = $conn ->insert_id; //返回上次查询中自增量的ID 
  
 $date = date("Y-m-d"); 
  
 $query ="insert into orders values 
  ('','". $customerid ."','". $_SESSION['total_price'] ."','". $date ."','PARTIAL','". $ship_name ."','". $ship_address ."','". $ship_city ."','". $ship_state ."','". $ship_zip ."','". $ship_country ."')"; 
   
 $result = $conn ->query($query); 
 if(!$result) 
  return false; 
  
 $query = "select orderid from orders where 
   customerid ='". $customerid ."' and 
   amount > (". $_SESSION['total_price'] ."-.001) and 
   amount < (". $_SESSION['total_price'] ."+.001) and 
   date ='". $date ."' and 
   order_status = 'PARTIAL' and 
   ship_name ='". $ship_name ."' and 
   ship_address ='". $ship_address ."' and 
   ship_city ='". $ship_city ."' and 
   ship_state ='". $ship_state ."' and 
   ship_zip ='". $ship_zip ."' and 
   ship_country ='". $ship_country ."'"; 
  
 $result = $conn ->query($query); 
  
 if($result ->num_rows > 0) 
 { 
  $order = $result ->fetch_object(); 
  $orderid = $order ->orderid; 
 } 
 else 
  return false; 
  
 foreach($_SESSION['cart'] as $isbn => $quantity) 
 { 
  $detail = get_book_details($isbn); 
  $query = "delete from order_items where 
   orderid = '". $orderid ."' and isbn = '". $isbn ."'"; 
  $result = $conn ->query($query); 
  
  $query = "insert into order_items values 
   ('". $orderid ."','". $isbn ."',". $detail['price'] .",$quantity)"; 
  $result = $conn ->query($query); 
  if(!$result) 
  return false; 
 } 
  
 //事务关闭,开启自动提交 
 $conn ->commit(); 
 $conn ->autocommit(true); 
  
 return $orderid; 
 } 

登入後複製

5.9 output_fns.php文件中的函数display_shipping()

function display_shipping($shipping) //输出包含运费的总价 
 { 
 &#63;> 
  <table border="0" width="100%" cellspacing="0"> 
  <tr> 
   <td align="left">Shipping</td> 
   <td align="right"> <&#63;php echo number_format($shipping, 2); &#63;></td> 
  </tr> 
  <tr> 
   <th bgcolor="#cccccc" align="left">TOTAL INCLUDING SHIPPING</th> 
   <th bgcolor="#cccccc" align="right">$ <&#63;php echo number_format($shipping+$_SESSION['total_price'], 2); &#63;></th> 
  </tr> 
  </table> 
  <br /> 
 <&#63;php 
 } 

登入後複製

5.10 output_fns.php文件中的函数display_card_form()

function display_card_form($name) //输出信用卡信息 
 { 
 &#63;> 
  <table border="0" width="100%" cellspacing="0"> 
  <form action="process.php" method="post"> 
   <tr> 
   <th colspan="2" bgcolor="#cccccc">Credit Card Details</th> 
   </tr> 
   <tr> 
   <td>Type</td> 
   <td> 
    <select name="card_type"> 
    <option value="VISA">VISA</option> 
    <option value="MasterCard">MasterCard</option> 
    <option value="American Express">American Express</option> 
    </select> 
   </td> 
   </tr> 
   <tr> 
   <td>Number</td> 
   <td><input type="text" name="card_number" value="" maxlength="16" size="40"/></td> 
   </tr> 
   <tr> 
   <td>AMEX code (if required)</td> 
   <td><input type="text" name="amex_code" value="" maxlength="4" size="4"/></td> 
   </tr> 
   <tr> 
   <td>Expiry Date</td> 
   <td>Month 
    <select name="card_month"> 
    <option value="01">01</option> 
    <option value="02">02</option> 
    <option value="03">03</option> 
    <option value="04">04</option> 
    <option value="05">05</option> 
    <option value="06">06</option> 
    <option value="07">07</option> 
    <option value="08">08</option> 
    <option value="09">09</option> 
    <option value="10">10</option> 
    <option value="11">11</option> 
    <option value="12">12</option> 
    </select> 
    Year 
    <select name="card_year"> 
    <&#63;php 
     for($y = date("Y"); $y < date("Y") + 10; $y++) 
     echo "<option value =\"". $y ."\">" . $y ."</option>"; 
    &#63;> 
    </select> 
   </td> 
   </tr> 
   <tr> 
   <td>Name on Card</td> 
   <td><input type="text" name="card_name" value="<&#63;php echo $name; &#63;>" maxlength="40" size="40"/></td> 
   </tr> 
   <tr> 
   <td colspan="2" align="center"> 
    <p> 
    <strong>Please press Purchase to confirm yout purchase, or Continue Shopping to add or remove items</strong> 
    </p> 
    <&#63;php display_form_button('purchase','Purchase These Items'); &#63;> 
   </td> 
   </tr> 
  </table> 
 <&#63;php 
 }
登入後複製

5.11 db_fns.php文件中的函数db_connect()

function db_connect() //连接数据库 
 { 
 $result = new mysqli('localhost','book_sc','password','book_sc'); 
 if(!$result) //连接失败 
  return false; 
 $result ->autocommit(true); 
 return $result; 
 } 

登入後複製

6、实现付款


已填写好信息的信用卡详细信息


购物成功

由以下代码实现:
6.1 process.php

<&#63;php 
 
/** 
 * @author switch 
 * @copyright 2015 
 * 处理付款细节,将订单添加到数据库 
 */ 
 //require_once语句和require语句完全相同,唯一区别是PHP会检查该文件是否已经被包含过,如果是则不会再次包含。 
 require_once('book_sc_fns.php'); 
 
 session_start(); 
 
 do_html_header('Checkout'); 
 
 //创建变量 
 $card_type = $_POST['card_type']; 
 $card_number = $_POST['card_number']; 
 $card_month = $_POST['card_month']; 
 $card_year = $_POST['card_year']; 
 $card_name = $_POST['card_name']; 
 
 if(($_SESSION['cart']) && ($card_type) && ($card_number) && ($card_month) && ($card_year) &&($card_name)) 
 { 
 //显示没有图片,不允许更改数量的购物车 
 display_cart($_SESSION['cart'],false,0); 
  
 display_shipping(calculate_shipping_cost()); 
  
 if(process_card($_POST)) 
 { 
  //清空购物车 
  session_destroy(); 
  //这里可以写一些关于信用卡接口调用的函数,调用银行写好的接口 
  echo "<p>Thank you for shopping with us. Your order has been placed.</p>"; 
  
  display_button("index.php","continue-shopping","Continue Shopping"); 
 } 
 else 
 { 
  echo "<p>Could not process your card. Please contact the card issuer or try again.</p>"; 
  display_button("purchase.php","back","Back"); 
 } 
 } 
 else 
 { 
 echo "<p>You did not fill in all the fields,please try again.</p><hr/>"; 
 display_button("purchase.php","back","Back"); 
 } 
 do_html_footer(); 
&#63;> 

登入後複製

以上就是php实现购物车功能的前篇,代码很详细,希望对大家的学习有所帮助,之后还有下篇分享给大家,不要错过。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1317
25
PHP教程
1268
29
C# 教程
1246
24
在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

php程序在字符串中計數元音 php程序在字符串中計數元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符組成的序列,包括字母、數字和符號。本教程將學習如何使用不同的方法在PHP中計算給定字符串中元音的數量。英語中的元音是a、e、i、o、u,它們可以是大寫或小寫。 什麼是元音? 元音是代表特定語音的字母字符。英語中共有五個元音,包括大寫和小寫: a, e, i, o, u 示例 1 輸入:字符串 = "Tutorialspoint" 輸出:6 解釋 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。總共有 6 個元

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? 什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些? PHP的魔法方法包括:1.\_\_construct,用於初始化對象;2.\_\_destruct,用於清理資源;3.\_\_call,處理不存在的方法調用;4.\_\_get,實現動態屬性訪問;5.\_\_set,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

See all articles