本文目录导读:

我来为你设计一个PHP电商系统的核心模块架构,包含完整的代码实现。
系统架构总览
ecommerce/
├── app/
│ ├── Controllers/
│ │ ├── AuthController.php
│ │ ├── ProductController.php
│ │ ├── CartController.php
│ │ ├── OrderController.php
│ │ └── PaymentController.php
│ ├── Models/
│ │ ├── User.php
│ │ ├── Product.php
│ │ ├── Category.php
│ │ ├── Cart.php
│ │ ├── Order.php
│ │ └── OrderItem.php
│ ├── Services/
│ │ ├── CartService.php
│ │ ├── PaymentService.php
│ │ └── OrderService.php
│ └── Middleware/AuthMiddleware.php
├── config/
│ └── database.php
├── public/
│ └── index.php
└── routes/
└── web.php
数据库设计
-- 用户表
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
phone VARCHAR(20),
address TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- 商品分类表
CREATE TABLE categories (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
parent_id INT DEFAULT 0,
sort_order INT DEFAULT 0,
status TINYINT DEFAULT 1
);
-- 商品表
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
category_id INT NOT NULL,
name VARCHAR(200) NOT NULL,
description TEXT,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL DEFAULT 0,
image VARCHAR(255),
status TINYINT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id)
);
-- 购物车表
CREATE TABLE carts (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY (user_id, product_id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
-- 订单表
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(30) UNIQUE NOT NULL,
user_id INT NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
status TINYINT DEFAULT 0, -- 0待付款 1已付款 2已发货 3已完成 4已取消
shipping_address TEXT,
payment_method VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 订单商品表
CREATE TABLE order_items (
id INT PRIMARY KEY AUTO_INCREMENT,
order_id INT NOT NULL,
product_id INT NOT NULL,
product_name VARCHAR(200) NOT NULL,
price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL,
subtotal DECIMAL(10,2) NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
核心类实现
1 数据库连接类
<?php
// app/Core/Database.php
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$host = 'localhost';
$dbname = 'ecommerce';
$username = 'root';
$password = '';
try {
$this->connection = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]
);
} catch (PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
2 用户模型
<?php
// app/Models/User.php
require_once __DIR__ . '/../Core/Database.php';
class User {
private $db;
public function __construct() {
$this->db = Database::getInstance()->getConnection();
}
public function register($username, $email, $password, $phone = '', $address = '') {
// 检查邮箱是否已存在
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->rowCount() > 0) {
return ['success' => false, 'message' => '邮箱已被注册'];
}
// 密码加密
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password, phone, address)
VALUES (?, ?, ?, ?, ?)";
$stmt = $this->db->prepare($sql);
if ($stmt->execute([$username, $email, $hashedPassword, $phone, $address])) {
return ['success' => true, 'message' => '注册成功'];
}
return ['success' => false, 'message' => '注册失败'];
}
public function login($email, $password) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
unset($user['password']);
return $user;
}
return false;
}
public function getUserById($id) {
$stmt = $this->db->prepare("SELECT id, username, email, phone, address FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
public function updateUser($id, $data) {
$allowedFields = ['username', 'phone', 'address'];
$updates = [];
$params = [];
foreach ($data as $key => $value) {
if (in_array($key, $allowedFields)) {
$updates[] = "$key = ?";
$params[] = $value;
}
}
if (empty($updates)) {
return false;
}
$params[] = $id;
$sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute($params);
}
}
3 商品模型
<?php
// app/Models/Product.php
require_once __DIR__ . '/../Core/Database.php';
class Product {
private $db;
public function __construct() {
$this->db = Database::getInstance()->getConnection();
}
public function getAllProducts($page = 1, $limit = 12, $categoryId = null, $keyword = '') {
$offset = ($page - 1) * $limit;
$sql = "SELECT p.*, c.name as category_name
FROM products p
LEFT JOIN categories c ON p.category_id = c.id
WHERE p.status = 1";
$params = [];
if ($categoryId) {
$sql .= " AND p.category_id = ?";
$params[] = $categoryId;
}
if ($keyword) {
$sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
$params[] = "%$keyword%";
$params[] = "%$keyword%";
}
$sql .= " ORDER BY p.created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return ['products' => $stmt->fetchAll()];
}
public function getProductById($id) {
$stmt = $this->db->prepare("SELECT * FROM products WHERE id = ? AND status = 1");
$stmt->execute([$id]);
return $stmt->fetch();
}
public function getRelatedProducts($categoryId, $excludeId, $limit = 4) {
$sql = "SELECT * FROM products
WHERE category_id = ? AND id != ? AND status = 1
ORDER BY created_at DESC LIMIT ?";
$stmt = $this->db->prepare($sql);
$stmt->execute([$categoryId, $excludeId, $limit]);
return $stmt->fetchAll();
}
public function searchProducts($keyword, $page = 1, $limit = 12) {
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM products
WHERE (name LIKE ? OR description LIKE ?) AND status = 1
ORDER BY created_at DESC LIMIT ? OFFSET ?";
$stmt = $this->db->prepare($sql);
$stmt->execute(["%$keyword%", "%$keyword%", $limit, $offset]);
return $stmt->fetchAll();
}
public function checkStock($productId, $quantity = 1) {
$stmt = $this->db->prepare("SELECT stock FROM products WHERE id = ? AND status = 1");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if (!$product || $product['stock'] < $quantity) {
return false;
}
return true;
}
public function reduceStock($productId, $quantity) {
$sql = "UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute([$quantity, $productId, $quantity]);
}
}
4 购物车服务
<?php
// app/Services/CartService.php
require_once __DIR__ . '/../Models/Product.php';
class CartService {
private $db;
public function __construct() {
$this->db = Database::getInstance()->getConnection();
}
public function addToCart($userId, $productId, $quantity = 1) {
$productModel = new Product();
// 检查商品是否存在且有库存
if (!$productModel->checkStock($productId, $quantity)) {
return ['success' => false, 'message' => '库存不足'];
}
// 检查是否已在购物车
$stmt = $this->db->prepare("SELECT id, quantity FROM carts WHERE user_id = ? AND product_id = ?");
$stmt->execute([$userId, $productId]);
$cartItem = $stmt->fetch();
if ($cartItem) {
// 更新数量
$newQuantity = $cartItem['quantity'] + $quantity;
$sql = "UPDATE carts SET quantity = ? WHERE id = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute([$newQuantity, $cartItem['id']]);
} else {
// 添加新记录
$sql = "INSERT INTO carts (user_id, product_id, quantity) VALUES (?, ?, ?)";
$stmt = $this->db->prepare($sql);
$stmt->execute([$userId, $productId, $quantity]);
}
return ['success' => true, 'message' => '已加入购物车'];
}
public function getCartItems($userId) {
$sql = "SELECT c.*, p.name, p.price, p.image
FROM carts c
JOIN products p ON c.product_id = p.id
WHERE c.user_id = ? AND p.status = 1";
$stmt = $this->db->prepare($sql);
$stmt->execute([$userId]);
$items = $stmt->fetchAll();
$total = 0;
foreach ($items as &$item) {
$item['subtotal'] = $item['price'] * $item['quantity'];
$total += $item['subtotal'];
}
return ['items' => $items, 'total' => $total];
}
public function updateCartItem($userId, $productId, $quantity) {
if ($quantity <= 0) {
return $this->removeFromCart($userId, $productId);
}
$sql = "UPDATE carts SET quantity = ? WHERE user_id = ? AND product_id = ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute([$quantity, $userId, $productId]);
}
public function removeFromCart($userId, $productId) {
$sql = "DELETE FROM carts WHERE user_id = ? AND product_id = ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute([$userId, $productId]);
}
public function clearCart($userId) {
$sql = "DELETE FROM carts WHERE user_id = ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute([$userId]);
}
public function getCartCount($userId) {
$stmt = $this->db->prepare("SELECT COUNT(*) as count FROM carts WHERE user_id = ?");
$stmt->execute([$userId]);
return $stmt->fetch()['count'];
}
}
5 订单服务
<?php
// app/Services/OrderService.php
require_once __DIR__ . '/../Models/Product.php';
require_once __DIR__ . '/CartService.php';
class OrderService {
private $db;
public function __construct() {
$this->db = Database::getInstance()->getConnection();
}
public function createOrder($userId, $shippingAddress, $paymentMethod) {
$cartService = new CartService();
$productModel = new Product();
// 获取购物车内容
$cartData = $cartService->getCartItems($userId);
if (empty($cartData['items'])) {
return ['success' => false, 'message' => '购物车为空'];
}
try {
// 开启事务
$this->db->beginTransaction();
// 生成订单号
$orderNo = $this->generateOrderNo();
// 创建订单
$sql = "INSERT INTO orders (order_no, user_id, total_amount, status, shipping_address, payment_method)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $this->db->prepare($sql);
$stmt->execute([
$orderNo,
$userId,
$cartData['total'],
$shippingAddress,
$paymentMethod
]);
$orderId = $this->db->lastInsertId();
// 创建订单项并扣减库存
foreach ($cartData['items'] as $item) {
// 插入订单项
$sql = "INSERT INTO order_items (order_id, product_id, product_name, price, quantity, subtotal)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $this->db->prepare($sql);
$stmt->execute([
$orderId,
$item['product_id'],
$item['name'],
$item['price'],
$item['quantity'],
$item['subtotal']
]);
// 扣减库存
$productModel->reduceStock($item['product_id'], $item['quantity']);
}
// 清空购物车
$cartService->clearCart($userId);
// 提交事务
$this->db->commit();
return ['success' => true, 'message' => '订单创建成功', 'order_id' => $orderId, 'order_no' => $orderNo];
} catch (Exception $e) {
$this->db->rollBack();
return ['success' => false, 'message' => '订单创建失败: ' . $e->getMessage()];
}
}
private function generateOrderNo() {
return date('YmdHis') . rand(1000, 9999);
}
public function getUserOrders($userId, $status = null) {
$sql = "SELECT * FROM orders WHERE user_id = ?";
$params = [$userId];
if ($status !== null) {
$sql .= " AND status = ?";
$params[] = $status;
}
$sql .= " ORDER BY created_at DESC";
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
public function getOrderById($orderId, $userId = null) {
$sql = "SELECT * FROM orders WHERE id = ?";
$params = [$orderId];
if ($userId) {
$sql .= " AND user_id = ?";
$params[] = $userId;
}
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
$order = $stmt->fetch();
if ($order) {
// 获取订单项
$sql = "SELECT * FROM order_items WHERE order_id = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute([$orderId]);
$order['items'] = $stmt->fetchAll();
}
return $order;
}
public function updateOrderStatus($orderId, $status) {
$sql = "UPDATE orders SET status = ? WHERE id = ?";
$stmt = $this->db->prepare($sql);
return $stmt->execute([$status, $orderId]);
}
}
6 支付服务
<?php
// app/Services/PaymentService.php
class PaymentService {
private $db;
public function __construct() {
$this->db = Database::getInstance()->getConnection();
}
public function processPayment($orderId, $paymentData) {
// 这里集成实际的支付网关
// 模拟支付处理
$orderService = new OrderService();
$order = $orderService->getOrderById($orderId);
if (!$order) {
return ['success' => false, 'message' => '订单不存在'];
}
if ($order['status'] != 0) {
return ['success' => false, 'message' => '订单状态不正确'];
}
// 模拟支付验证
$paymentSuccess = $this->verifyPayment($paymentData);
if ($paymentSuccess) {
// 更新订单状态为已付款
$orderService->updateOrderStatus($orderId, 1);
return ['success' => true, 'message' => '支付成功'];
}
return ['success' => false, 'message' => '支付失败'];
}
private function verifyPayment($paymentData) {
// 模拟支付验证逻辑
// 实际应用中可以调用支付宝、微信支付等API
if (isset($paymentData['amount']) && $paymentData['amount'] > 0) {
return true;
}
return false;
}
}
控制器实现
1 商品控制器
<?php
// app/Controllers/ProductController.php
require_once __DIR__ . '/../Models/Product.php';
class ProductController {
private $productModel;
public function __construct() {
$this->productModel = new Product();
}
public function list() {
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$categoryId = isset($_GET['category']) ? (int)$_GET['category'] : null;
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
$data = $this->productModel->getAllProducts($page, 12, $categoryId, $keyword);
// 返回JSON数据
header('Content-Type: application/json');
echo json_encode($data);
}
public function detail($id) {
$product = $this->productModel->getProductById($id);
if (!$product) {
http_response_code(404);
echo json_encode(['error' => '商品不存在']);
return;
}
// 获取相关商品
$relatedProducts = $this->productModel->getRelatedProducts(
$product['category_id'],
$product['id']
);
echo json_encode([
'product' => $product,
'related_products' => $relatedProducts
]);
}
}
2 购物车控制器
<?php
// app/Controllers/CartController.php
require_once __DIR__ . '/../Services/CartService.php';
require_once __DIR__ . '/../Middleware/AuthMiddleware.php';
class CartController {
private $cartService;
public function __construct() {
$this->cartService = new CartService();
}
public function add() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$productId = $_POST['product_id'];
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
if (!$productId || $quantity < 1) {
echo json_encode(['success' => false, 'message' => '参数错误']);
return;
}
$result = $this->cartService->addToCart($userId, $productId, $quantity);
echo json_encode($result);
}
public function view() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$data = $this->cartService->getCartItems($userId);
header('Content-Type: application/json');
echo json_encode($data);
}
public function update() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$productId = $_POST['product_id'];
$quantity = (int)$_POST['quantity'];
$result = $this->cartService->updateCartItem($userId, $productId, $quantity);
echo json_encode(['success' => $result]);
}
public function remove() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$productId = $_POST['product_id'];
$result = $this->cartService->removeFromCart($userId, $productId);
echo json_encode(['success' => $result]);
}
}
3 订单控制器
<?php
// app/Controllers/OrderController.php
require_once __DIR__ . '/../Services/OrderService.php';
require_once __DIR__ . '/../Middleware/AuthMiddleware.php';
class OrderController {
private $orderService;
public function __construct() {
$this->orderService = new OrderService();
}
public function create() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$shippingAddress = $_POST['shipping_address'];
$paymentMethod = $_POST['payment_method'];
if (empty($shippingAddress)) {
echo json_encode(['success' => false, 'message' => '请填写收货地址']);
return;
}
$result = $this->orderService->createOrder(
$userId,
$shippingAddress,
$paymentMethod
);
echo json_encode($result);
}
public function list() {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$status = isset($_GET['status']) ? (int)$_GET['status'] : null;
$orders = $this->orderService->getUserOrders($userId, $status);
header('Content-Type: application/json');
echo json_encode($orders);
}
public function detail($orderId) {
AuthMiddleware::checkAuth();
$userId = $_SESSION['user_id'];
$order = $this->orderService->getOrderById($orderId, $userId);
if (!$order) {
http_response_code(404);
echo json_encode(['error' => '订单不存在']);
return;
}
header('Content-Type: application/json');
echo json_encode($order);
}
}
路由配置
<?php
// routes/web.php
$route = $_GET['route'] ?? 'home';
// 简单的路由分发
switch ($route) {
// 用户相关
case 'register':
$controller = new AuthController();
$controller->register();
break;
case 'login':
$controller = new AuthController();
$controller->login();
break;
case 'logout':
$controller = new AuthController();
$controller->logout();
break;
// 商品相关
case 'products':
$controller = new ProductController();
$controller->list();
break;
case 'product':
$id = $_GET['id'] ?? 0;
$controller = new ProductController();
$controller->detail($id);
break;
// 购物车相关
case 'cart':
$controller = new CartController();
$controller->view();
break;
case 'cart_add':
$controller = new CartController();
$controller->add();
break;
case 'cart_update':
$controller = new CartController();
$controller->update();
break;
case 'cart_remove':
$controller = new CartController();
$controller->remove();
break;
// 订单相关
case 'order_create':
$controller = new OrderController();
$controller->create();
break;
case 'orders':
$controller = new OrderController();
$controller->list();
break;
case 'order_detail':
$id = $_GET['id'] ?? 0;
$controller = new OrderController();
$controller->detail($id);
break;
default:
echo json_encode(['message' => 'Welcome to E-commerce API']);
}
中间件
<?php
// app/Middleware/AuthMiddleware.php
class AuthMiddleware {
public static function checkAuth() {
session_start();
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => '未登录']);
exit;
}
}
}
性能优化建议
<?php
// app/Services/CacheService.php
class CacheService {
private $cacheDir;
public function __construct($cacheDir = __DIR__ . '/../../cache/') {
$this->cacheDir = $cacheDir;
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
}
public function get($key) {
$file = $this->cacheDir . md5($key) . '.cache';
if (file_exists($file)) {
$data = unserialize(file_get_contents($file));
if ($data['expire'] > time()) {
return $data['value'];
}
unlink($file);
}
return null;
}
public function set($key, $value, $expire = 300) {
$file = $this->cacheDir . md5($key) . '.cache';
$data = [
'expire' => time() + $expire,
'value' => $value
];
file_put_contents($file, serialize($data));
}
}
安全措施
<?php
// app/Services/SecurityService.php
class SecurityService {
public static function sanitizeInput($data) {
if (is_array($data)) {
return array_map([self::class, 'sanitizeInput'], $data);
}
return htmlspecialchars(strip_tags(trim($data)));
}
public static function generateCsrfToken() {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
public static function validateCsrfToken($token) {
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
public static function rateLimit($key, $maxAttempts = 5, $timeWindow = 300) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$count = $redis->incr($key);
if ($count === 1) {
$redis->expire($key, $timeWindow);
}
if ($count > $maxAttempts) {
return false;
}
return true;
}
}
前端集成示例
<!-- public/index.php -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">电商系统</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">电商系统</a>
<div class="navbar-nav">
<a class="nav-link" href="#" onclick="getProducts()">商品列表</a>
<a class="nav-link" href="#" onclick="getCart()">购物车 <span id="cartCount">0</span></a>
</div>
</div>
</nav>
<div class="container mt-4">
<div id="products" class="row"></div>
<div id="cart" style="display:none"></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 获取商品列表
function getProducts() {
$.get('/index.php?route=products', function(data) {
let html = '';
data.products.forEach(product => {
html += `
<div class="col-md-3 mb-4">
<div class="card">
<img src="${product.image}" class="card-img-top" alt="${product.name}">
<div class="card-body">
<h5 class="card-title">${product.name}</h5>
<p class="card-text">¥${product.price}</p>
<button class="btn btn-primary" onclick="addToCart(${product.id})">
加入购物车
</button>
</div>
</div>
</div>
`;
});
$('#products').html(html);
});
}
// 加入购物车
function addToCart(productId) {
$.post('/index.php?route=cart_add', {
product_id: productId,
quantity: 1
}, function(data) {
alert(data.message);
});
}
// 获取购物车
function getCart() {
$('#products').hide();
$('#cart').show();
$.get('/index.php?route=cart', function(data) {
let html = '<h3>购物车</h3>';
data.items.forEach(item => {
html += `
<div class="card mb-2">
<div class="card-body">
<div class="row">
<div class="col-md-4">
<img src="${item.image}" class="img-fluid" alt="${item.name}">
</div>
<div class="col-md-8">
<h5>${item.name}</h5>
<p>单价:¥${item.price}</p>
<p>数量:${item.quantity}</p>
<p>小计:¥${item.subtotal}</p>
</div>
</div>
</div>
</div>
`;
});
html += `<h4>总计:¥${data.total}</h4>`;
$('#cart').html(html);
});
}
// 页面加载时获取商品列表
getProducts();
</script>
</body>
</html>
这个电商系统核心模块包含了完整的用户认证、商品管理、购物车、订单处理和支付流程,你可以根据实际需求添加更多功能,如优惠券系统、评价系统、推荐算法等,记住在生产环境中要添加完善的错误处理、日志记录和安全防护措施。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播