php+bootstrap+jquery+mysql实现购物车项目案例

获取源码

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

介绍

使用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
posted @ 2023-03-09 16:30  一锤子技术员  阅读(14)  评论(0编辑  收藏  举报  来源