php 实现购物车
实现购物车的基本思路
购物车功能通常涉及添加商品、删除商品、更新数量、计算总价等操作。PHP可以通过会话(Session)或数据库存储购物车数据。以下是两种常见实现方式。
使用Session实现购物车
Session适合临时存储购物车数据,用户关闭浏览器后数据会丢失。
初始化购物车
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
添加商品到购物车
function addToCart($productId, $quantity, $price) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$productId] = array(
'quantity' => $quantity,
'price' => $price
);
}
}
从购物车移除商品
function removeFromCart($productId) {
if (isset($_SESSION['cart'][$productId])) {
unset($_SESSION['cart'][$productId]);
}
}
更新商品数量
function updateCartItem($productId, $quantity) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] = $quantity;
}
}
计算购物车总价
function calculateTotal() {
$total = 0;
foreach ($_SESSION['cart'] as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
使用数据库实现购物车
数据库适合持久化存储购物车数据,用户关闭浏览器后数据仍然保留。
创建购物车表
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
添加商品到购物车
function addToCart($userId, $productId, $quantity) {
// 检查是否已存在
$stmt = $pdo->prepare("SELECT * FROM cart WHERE user_id = ? AND product_id = ?");
$stmt->execute([$userId, $productId]);
$existingItem = $stmt->fetch();
if ($existingItem) {
// 更新数量
$newQuantity = $existingItem['quantity'] + $quantity;
$stmt = $pdo->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
$stmt->execute([$newQuantity, $existingItem['id']]);
} else {
// 新增记录
$stmt = $pdo->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
$stmt->execute([$userId, $productId, $quantity]);
}
}
获取用户购物车
function getUserCart($userId) {
$stmt = $pdo->prepare("
SELECT c.*, p.name, p.price
FROM cart c
JOIN products p ON c.product_id = p.id
WHERE c.user_id = ?
");
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
前端交互示例
添加商品到购物车(AJAX)
$('.add-to-cart').click(function() {
let productId = $(this).data('product-id');
$.post('add_to_cart.php', {productId: productId}, function(response) {
alert('商品已添加到购物车');
});
});
安全注意事项
验证用户输入,防止SQL注入和XSS攻击。对数量和价格进行严格验证,确保为正数。
$quantity = filter_var($_POST['quantity'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($quantity === false) {
die('数量无效');
}
性能优化建议
对于大型电商网站,可以考虑使用Redis等内存数据库存储购物车数据,提高读写性能。定期清理长时间未活动的购物车数据。







