侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

php实现购物车功能(上)

php  /  管理员 发布于 7年前   213

本文分两篇为大家介绍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

Please choose a category:

"; $cat_array = get_categories(); //从数据库获取目录 display_categories($cat_array); //显示目录链接 if(isset($_SESSION['admin_user'])) //如果是管理员,显示管理员操作 display_button("admin.php","admin-menu","Admin Menu"); do_html_footer(); //页尾 ?>

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 "

No categories currently available

"; return; } echo "
    "; foreach($cat_array as $row) { $url = "show_cat.php?catid=". $row['catid']; $title = $row['catname']; echo "
  • "; do_html_URL($url,$title); echo "
  • "; } echo "
"; echo "
"; }

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

 

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 "

No books currently available in this category

"; else //有图书,建表 { echo ""; foreach($book_array as $row) { $url = "show_book.php?isbn=". $row['isbn']; echo ""; } echo "
"; // 如果图片存在 if(@file_exists("images/". $row['isbn'] .".jpg")) { $title = ""; do_html_URL($url,$title); } else echo " "; echo ""; $title = $row['title'] ." by ". $row['author']; do_html_URL($url,$title); echo "
"; } echo "
"; }


PHP and MySQL Web Development的详细信息

由以下代码实现:

4.10 show_book.php

 

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 "";   // 如果图片存在   if(@file_exists("images/". $book['isbn'] .".jpg"))   {   $size = getimagesize("images/". $book['isbn'] .".jpg");   if(($size[0] > 0) && ($size[1] > 0))   {    echo "";   }   }   echo "
    "; echo "
  • Author:"; echo $book['author']; echo "
  • ISBN:"; echo $book['isbn']; echo "
  • Our Price:"; echo number_format($book['price'],2); echo "
  • Description:"; echo $book['description']; echo "
"; } else { echo "

The details of this book cannot be displayed at this time.

"; } echo "
"; }

5、实现购物车


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


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

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

 $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 "

There are no items in your cart


"; } $target = "index.php"; //如果只有一种物品添加到购物车,可以继续购物 if($new) { $details = get_book_details($new); if($details['catid']) { $target = "show_cat.php?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(); ?>

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

function display_cart($cart,$change = true,$images = 1) //显示购物车  {  echo "";  //输出购物车中每一项  foreach($cart as $isbn => $qty)  {   $book = get_book_details($isbn);   echo "";   if($images == true)   {   echo "";   }   echo "\n";  }     //总数  echo "";    //保存按钮  if($change == true)  {   echo "";  }  echo "
Item Price Quantity Total
"; if(file_exists("images/". $isbn .".jpg")) { $size = getimagesize("images/". $isbn .".jpg"); if(($size[0] > 0) && ($size[1] > 1)) //图片长宽 { echo ""; } } else echo " "; echo " ". $book['title'] ." by". $book['author'] ." \$". number_format($book['price'],2) .""; //如果允许更改数量 if ($change == true) { echo ""; } else { echo $qty; } echo "\$".number_format($book['price']*$qty,2)."
". $_SESSION['items'] ." \$". number_format($_SESSION['total_price'],2) ."
"; }

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

Thers are no items in your cart

"; } display_button("show_cart.php","continue-shopping","Continue Shopping"); do_html_footer(); ?>

5.6 output_fns.php文件中的display_checkout_form()

function display_checkout_form() //输出付款台界面  {  ?>   
Your Details
Name
Address
City/Suburb
State/Province
Postal Code or Zip Code
Country
Shipping Address(leave blank if as above)
Name
Address
City/Suburb
State/Province
Postal Code or Zip Code
Country

Please press Purchase to confirm your purchase, or Continue Shopping to add or remove items.


   

已填写好信息的订单


获取客户信用卡信息

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

Could not store data, please try again.


"; display_button('checkout.php','back','Back'); } } else { echo "

You did not fill in all the fields, please try again.


"; display_button('checkout.php','back','Back'); } do_html_footer(); ?>

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) //输出包含运费的总价  {  ?>   
Shipping
TOTAL INCLUDING SHIPPING $

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

function display_card_form($name) //输出信用卡信息  {  ?>   
Credit Card Details
Type
Number
AMEX code (if required)
Expiry Date Month Year
Name on Card

Please press Purchase to confirm yout purchase, or Continue Shopping to add or remove items

 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

Thank you for shopping with us. Your order has been placed.

"; display_button("index.php","continue-shopping","Continue Shopping"); } else { echo "

Could not process your card. Please contact the card issuer or try again.

"; display_button("purchase.php","back","Back"); } } else { echo "

You did not fill in all the fields,please try again.


"; display_button("purchase.php","back","Back"); } do_html_footer(); ?>

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

您可能感兴趣的文章:

  • php 购物车完整实现代码
  • php购物车实现代码
  • php 购物车的例子
  • php网上商城购物车设计代码分享
  • 深入PHP购物车模块功能分析(函数讲解,附源码)
  • PHP购物车类Cart.class.php定义与用法示例
  • php实现仿写CodeIgniter的购物车类
  • PHP实现的购物车类实例
  • PHP实现的比较完善的购物车类
  • php实现保存周期为1天的购物车类


  • 上一条:
    php实现购物车功能(下)
    下一条:
    WordPress开发中自定义菜单的相关PHP函数使用简介
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客