获取源码

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

介绍

使用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. java - ArrayList的使用

    package list; import java.util.ArrayList; import demo.Hero; public class ListTs { public static void ...

  2. C++静态库与动态库执行过程深入

    静态库与动态库 静态库 基本使用 静态库是将一组完整的功能,如一个提供了完整运算的计算器,进行封装为一个.a或.lib文件. 使用时仅需要在使用处include这个静态库的头文件.而后在编译时添加-L ...

  3. [转帖]经典的 Fork 炸弹解析

    https://linux.cn/article-5685-1.html Jaromil 在 2002 年设计了最为精简的一个 Linux Fork 炸弹,整行代码只有 13 个字符(包括空格在内,空 ...

  4. [转帖]Shell编程之正则表达式与文本处理器(grep、sort、uniq、tr、cut)

    目录 正则表达式概念 正则表达式的作用 元字符 grep命令在文本中查找指定的字符串 sort命令排序 uniq命令快捷去重 tr命令替换.压缩和删除 cut命令快速裁剪命令 expr substr ...

  5. [转帖]dd 自动压测与结果解析脚本

    测试串行.并发.读.写 4类操作,每类操作又可以指定各种bs及count值,循环压测.每种场景一般执行3次,取平均值. 一. 串行写 #!/bin/sh bs_list=(256k 1024k 10M ...

  6. 【转帖】isolcpus功能与使用

    isolcpus功能存在已久,笔者追溯v2.6.11(2005年)那时内核就已经存在了isolcpus功能.根据kernel-parameters.txt 上的解释,"isolcpus功能用 ...

  7. [转帖]ubuntu下配置iptables、ufw端口转发

    iptables 端口转发(CentOS) 注意:一来一去 在中转服务器操作 iptables -t nat -A PREROUTING -p tcp --dport [端口号] -j DNAT -- ...

  8. [转帖]Linux性能调优之内存负载调优的一些笔记

    https://zhuanlan.zhihu.com/p/548770928 写在前面 整理一些Linux内存调优的笔记,分享给小伙伴 博文没有涉及的Demo,理论方法偏多,可以用作内存调优入门 博文 ...

  9. 获取特定端口java进程的路径的shell脚本

    获取特定端口java进程的路径的shell脚本 ll /proc/`lsof -i:5200 |grep ^java |awk '{print $2}' |uniq` |grep cwd |cut - ...

  10. 【小分享】vm-storage中,计算metric的平均长度

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 表达式如下: sum by (type) (vm_cach ...