php购物车实现
PHP购物车实现方法
使用PHP实现购物车功能可以通过会话(Session)或数据库存储购物车数据。以下是两种常见的实现方式:
基于Session的购物车实现

session_start();
// 添加商品到购物车
if (isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
// 从购物车移除商品
if (isset($_GET['remove'])) {
$product_id = $_GET['remove'];
unset($_SESSION['cart'][$product_id]);
}
// 更新购物车数量
if (isset($_POST['update_cart'])) {
foreach ($_POST['quantity'] as $product_id => $quantity) {
$_SESSION['cart'][$product_id] = $quantity;
}
}
基于数据库的购物车实现
// 数据库连接
$db = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
// 添加商品到购物车
if (isset($_POST['add_to_cart'])) {
$user_id = $_SESSION['user_id'];
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
$stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity)
VALUES (:user_id, :product_id, :quantity)
ON DUPLICATE KEY UPDATE quantity = quantity + :quantity");
$stmt->execute([
':user_id' => $user_id,
':product_id' => $product_id,
':quantity' => $quantity
]);
}
// 获取用户购物车内容
function getCartItems($user_id) {
global $db;
$stmt = $db->prepare("SELECT p.*, c.quantity FROM cart c
JOIN products p ON c.product_id = p.id
WHERE c.user_id = :user_id");
$stmt->execute([':user_id' => $user_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
购物车前端展示
<!-- 购物车页面示例 -->
<div class="cart-container">
<?php foreach ($_SESSION['cart'] as $product_id => $quantity): ?>
<div class="cart-item">
<img src="product_images/<?php echo $product_id; ?>.jpg">
<h3><?php echo getProductName($product_id); ?></h3>
<p>价格: $<?php echo getProductPrice($product_id); ?></p>
<form method="post">
<input type="number" name="quantity[<?php echo $product_id; ?>]"
value="<?php echo $quantity; ?>" min="1">
<button type="submit" name="update_cart">更新</button>
</form>
<a href="?remove=<?php echo $product_id; ?>">移除</a>
</div>
<?php endforeach; ?>
<div class="cart-total">
总计: $<?php echo calculateCartTotal(); ?>
</div>
</div>
购物车功能扩展
AJAX实现无刷新购物车

// jQuery示例
$('.add-to-cart').click(function() {
var product_id = $(this).data('product-id');
$.post('add_to_cart.php', {
product_id: product_id,
quantity: 1
}, function(response) {
$('#cart-count').text(response.cart_count);
}, 'json');
});
购物车安全考虑
- 验证所有输入数据
- 使用预处理语句防止SQL注入
- 限制商品数量范围
- 实现CSRF保护
性能优化建议
- 对频繁访问的购物车数据使用缓存
- 批量更新数据库操作
- 限制购物车商品数量
以上代码示例展示了PHP购物车的基本实现方法,可以根据具体需求进行扩展和修改。






