获取源码

一键三连后,评论区留下邮箱安排发送:)

介绍

使用php,bootstrap,jquery,mysql实现的简易购物车案例。

通过本案例,你将学习到以下知识点:

  • php 操作 mysql 实现增删改查
  • 掌握 php 常用数组函数
  • 掌握 php $_session 对象使用
  • 掌握 php 基本的面向对象编程知识
  • 掌握 bootstrap 基本的布局和样式组件使用

技术栈

  • php7.0+
  • bootstrap4.0+
  • jquery
  • mysql5.7

开发步骤

只展示核心代码,完整项目请按文章开头说明获取。

项目概览

创建表结构

CREATE TABLE `products` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`sku` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL
)

php连接mysql

class DBConnection {
private $_dbHostname = "localhost";
private $_dbName = "demo_DB";
private $_dbUsername = "root";
private $_dbPassword = "";
private $_con; public function __construct() {
try {
$this->_con = new PDO("mysql:host=$this->_dbHostname;dbname=$this->_dbName", $this->_dbUsername, $this->_dbPassword);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
} }
// return Connection
public function returnConnection() {
return $this->_con;
}
}
?>

创建购物车类

class Cart
{ protected $db;
private $_sku;
public function setSKU($sku) {
$this->_sku = $sku;
} public function __construct() {
$this->db = new DBConnection();
$this->db = $this->db->returnConnection();
} // getAll Product
public function getAllProduct() {
try {
$sql = "SELECT * FROM products";
$stmt = $this->db->prepare($sql); $stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $result;
} catch (Exception $e) {
die("Oh noes! There's an error in the query!");
}
} // get Student
public function getProduct() {
try {
$sql = "SELECT * FROM products WHERE sku=:sku";
$stmt = $this->db->prepare($sql);
$data = [
'sku' => $this->_sku
];
$stmt->execute($data);
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
return $result;
} catch (Exception $e) {
die("Oh noes! There's an error in the query!");
}
} }

创建首页

<?php
session_start();
include('class/Cart.php');
$cart = new Cart();
$product_array = $cart->getAllProduct(); include('templates/header.php');
if(!empty($_SESSION["cart_item"])){
$count = count($_SESSION["cart_item"]);
} else {
$count = 0;
}
?>
<section class="showcase">
<div class="container">
<div class="pb-2 mt-4 mb-2 border-bottom">
<h2>Build Simple Shopping Cart using PHP <a style="float: right;" href="cart.php" class="btn btn-primary text-right"> Cart <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-light" id="cart-count"><?php print $count; ?></span></a></h2> </div>
<div class="row">
<div class="col" id="add-item-bag" style="width:100%;"></div> <div id="product-grid">
<?php
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
<div class="product-tile-footer">
<div class="product-title"><?php echo $product_array[$key]["name"]; ?></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
<div class="cart-action">
<input type="text" class="product-quantity" id="qty-<?php echo $product_array[$key]["id"]; ?>" name="quantity" value="1" size="2" />
<button type="button" class="btnAddAction" data-itemid="<?php echo $product_array[$key]["id"]; ?>" id="product-<?php echo $product_array[$key]["id"]; ?>" data-action="action" data-sku="<?php echo $product_array[$key]["sku"]; ?>" data-proname="<?php echo $product_array[$key]["sku"]; ?>"> Add to Cart</button>
</div>
</div>
</div>
<?php
}
}
?>
</div> </div> </div>
</section>
<?php include('templates/footer.php');?>

添加购物车逻辑

<?php
session_start();
$json = array();
include('class/Cart.php');
$cart = new Cart();
$cart->setSKU($_POST["sku"]);
$productByCode = $cart->getProduct(); if(!empty($_POST["quantity"])) {
$itemArray = array($productByCode["sku"]=>array('name'=>$productByCode["name"], 'sku'=>$productByCode["sku"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"], 'image'=>$productByCode["image"])); if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode["sku"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode["sku"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
$json['count'] = count($_SESSION["cart_item"]);
}
header('Content-Type: application/json');
echo json_encode($json);
?>

删除购物车商品逻辑

	<?php
session_start();
$json = array();
$total_quantity = 0;
$total_price = 0;
$count = 0;
if(!empty($_SESSION["cart_item"]) && count($_SESSION["cart_item"])>0) {
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_POST["sku"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
$bindHTML = '';
foreach ($_SESSION["cart_item"] as $item){
$total_quantity += $item["quantity"];
$total_price += ($item["price"]*$item["quantity"]);
}
$count = count($_SESSION["cart_item"]);
$json['total_quantity'] = $total_quantity;
$json['total_price'] = number_format($total_price, 2);
$json['count'] = $count;
}
header('Content-Type: application/json');
echo json_encode($json);
?>

部署方式

  1. 安装 php 运行环境,例如:使用 phpstudy
  2. 将文件夹phpcart复制到 apache 网站运行目录,例如:D:\program\phpstudy_pro\WWW
  3. phpstudy 中配置网站运行目录和端口
  4. 修改文件class\DBConnection.php中数据库信息
  5. 创建数据库phpcart导入 sql 文件sql/phpcart.sql
  6. 打开谷歌浏览器,访问路径:http://localhost:8082/phpcart/cart.php

php+bootstrap+jquery+mysql实现购物车项目案例的更多相关文章

  1. 使用Jquery+EasyUI 进行框架项目开发案例讲解之五 模块(菜单)管理源码分享

    http://www.cnblogs.com/huyong/p/3454012.html 使用Jquery+EasyUI 进行框架项目开发案例讲解之五  模块(菜单)管理源码分享    在上四篇文章 ...

  2. 使用Jquery+EasyUI 进行框架项目开发案例讲解之四 组织机构管理源码分享

    http://www.cnblogs.com/huyong/p/3404647.html 在上三篇文章  <使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享> ...

  3. 使用Jquery+EasyUI 进行框架项目开发案例讲解之三---角色管理源码分享

    使用Jquery+EasyUI 进行框架项目开发案例讲解之三 角色管理源码分享    在上两篇文章  <使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享> ...

  4. 使用Jquery+EasyUI 进行框架项目开发案例讲解之二---用户管理源码分享

    使用Jquery+EasyUI 进行框架项目开发案例讲解之二 用户管理源码分享   在上一篇文章<使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享>我们分享 ...

  5. 【推荐】使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享

    使用Jquery+EasyUI 进行框架项目开发案例讲解之一 员工管理源码分享   在开始讲解之前,我们先来看一下什么是Jquery EasyUI?jQuery EasyUI是一组基于jQuery的U ...

  6. 使用Jquery+EasyUI进行框架项目开发案例解说之中的一个---员工管理源代码分享

    使用Jquery+EasyUI 进行框架项目开发案例解说之中的一个 员工管理源代码分享 在開始解说之前,我们先来看一下什么是Jquery EasyUI?jQuery EasyUI是一组基于jQuery ...

  7. 使用Jquery+EasyUI 进行框架项目开发案例解说之二---用户管理源代码分享

    使用Jquery+EasyUI 进行框架项目开发案例解说之二 用户管理源代码分享  在上一篇文章<使用Jquery+EasyUI进行框架项目开发案例解说之中的一个---员工管理源代码分享> ...

  8. 使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享

    使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享 使用Jquery+EasyUI 进行框架项目开发案例讲解之一 员工管理源码分享    在开始讲解之前,我们先来看一下什 ...

  9. (转)使用Jquery+EasyUI 进行框架项目开发案例讲解之四---组织机构管理源码分享

    原文地址:http://www.cnblogs.com/huyong/p/3404647.html 在上三篇文章  <使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码 ...

  10. (转)使用Jquery+EasyUI进行框架项目开发案例讲解之一---员工管理源码分享

    原文地址:http://www.cnblogs.com/huyong/archive/2013/09/24/3334848.html 使用Jquery+EasyUI 进行框架项目开发案例讲解之一 员工 ...

随机推荐

  1. Laravel - 路由的多层嵌套

    Route::group(['prefix'=>'admin'],function(){ Route::get('/',function(){ return view('admin.articl ...

  2. [转帖]AMD处理器ZEN一代之国产化海光

    https://huataihuang.gitbook.io/cloud-atlas-draft/os/linux/kernel/cpu/amd_hygon   2020年国产化处理器受到了广泛的关注 ...

  3. Mysql8.0.32 union all创建视图无法使用中文模糊查询的坑

    Mysql8.0.32 union all创建视图无法使用中文模糊查询的坑 摘要 本周研发同事反馈现场有一个问题. 客户使用mysql的数据库(Windows平台) 然后在多表union all 创建 ...

  4. [转帖]一本正经的八卦一下CPU的自主可控

    https://zhuanlan.zhihu.com/p/36391482 (2018年的4月16日,美国商务部发布对中兴通讯出口权限禁令,禁止美国企业向其出售零部件,史称"中兴禁运事件&q ...

  5. [转贴]使用dbstart 和dbshut 脚本来自动化启动和关闭数据库

    使用dbstart 和dbshut 脚本来自动化启动和关闭数据库 https://www.cnblogs.com/snowers/p/3285281.htmldbshut 和 dbstart 使用db ...

  6. Springboot 内嵌Tomcat 的http连接池与thread的关系

    前言 最近看了很多tcp/ip 连接以及 IO相关的文章,但是依旧对数据库连接池等的部分不是很清楚, 所以这里仅是简单描述一下tomcat对应的http连接池数量的情况,不考虑与数据库的连接池的情况. ...

  7. Dubbo架构设计与源码解析(一) 架构设计

    作者:黄金 一.架构演变 单应用架构 ----> 垂直架构 ----> 分布式架构 ----> 微服务架构 ----> 云原生架构 二.Dubbo总体架构 1.角色职能 • C ...

  8. Ant Design Vue 单文件上传Upload

    单文件上传 <a-upload name="file" :beforeUpload="beforeUpload" :multiple="fals ...

  9. Golang zip压缩文件读写操作

    创建zip文件 golang提供了archive/zip包来处理zip压缩文件,下面通过一个简单的示例来展示golang如何创建zip压缩文件: func createZip(filename str ...

  10. 飞桨paddle遇到bug调试修正【迁移工具、版本兼容性】

    PaddlePaddlle强化学习及PARL框架{飞桨} [一]-环境配置+python入门教学 [二]-Parl基础命令 [三]-Notebook.&pdb.ipdb 调试 [四]-强化学习 ...