php如何实现购物车
PHP 实现购物车的基本方法
购物车功能通常包括添加商品、删除商品、更新数量、计算总价等。以下是几种常见的实现方式:
使用 Session 存储购物车数据
Session 是服务器端存储,适合临时保存用户购物车信息:
// 启动 Session
session_start();
// 添加商品到购物车
function addToCart($productId, $quantity) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] += $quantity;
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 从购物车移除商品
function removeFromCart($productId) {
if (isset($_SESSION['cart'][$productId])) {
unset($_SESSION['cart'][$productId]);
}
}
使用数据库存储购物车数据
适合需要持久化购物车数据的场景:

// 假设用户已登录,$userId 是当前用户ID
function addToCartDB($userId, $productId, $quantity) {
$db = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
$stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + ?");
$stmt->execute([$userId, $productId, $quantity, $quantity]);
}
计算购物车总价
结合商品表查询价格并计算:
function calculateTotal() {
$total = 0;
if (isset($_SESSION['cart'])) {
$db = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
foreach ($_SESSION['cart'] as $productId => $quantity) {
$stmt = $db->prepare("SELECT price FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch();
$total += $product['price'] * $quantity;
}
}
return $total;
}
前端交互示例
通过 AJAX 实现无刷新操作:

// 添加商品到购物车
function addToCart(productId) {
fetch('cart.php?action=add&id=' + productId)
.then(response => response.json())
.then(data => {
alert('已添加到购物车');
});
}
对应的 PHP 处理逻辑:
if ($_GET['action'] == 'add') {
addToCart($_GET['id'], 1);
echo json_encode(['success' => true]);
}
完整购物车类示例
封装成类更易于维护:
class ShoppingCart {
public function __construct() {
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
}
public function addItem($productId, $quantity) {
// 实现添加逻辑
}
public function removeItem($productId) {
// 实现移除逻辑
}
public function getTotal() {
// 实现计算总价
}
}
注意事项
- 对用户输入进行验证,防止 SQL 注入或非法数据
- 考虑并发操作时的数据一致性
- 对于未登录用户,可结合 Cookie 和 Session 存储临时购物车
- 定期清理长时间未处理的购物车数据
以上方法可根据实际项目需求组合使用,简单的电商系统使用 Session 即可,复杂的系统可能需要结合数据库实现。






