php购物车功能实现
数据库设计
创建必要的数据库表存储商品和购物车信息。通常需要products表和cart表:
-- 商品表
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2),
description TEXT,
image VARCHAR(100)
);
-- 购物车表(用户登录场景)
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (product_id) REFERENCES products(id)
);
会话存储实现
对于未登录用户,使用PHP的$_SESSION存储购物车数据:
// 初始化购物车
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// 添加商品到购物车
function addToCart($productId, $quantity = 1) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] += $quantity;
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 从购物车移除商品
function removeFromCart($productId) {
unset($_SESSION['cart'][$productId]);
}
数据库存储实现
对于已登录用户,购物车数据存入数据库:

// 添加商品到数据库购物车
function addToDBCart($userId, $productId, $quantity = 1) {
$existing = $db->query("SELECT * FROM cart WHERE user_id = $userId AND product_id = $productId");
if ($existing->num_rows > 0) {
$db->query("UPDATE cart SET quantity = quantity + $quantity WHERE user_id = $userId AND product_id = $productId");
} else {
$db->query("INSERT INTO cart (user_id, product_id, quantity) VALUES ($userId, $productId, $quantity)");
}
}
购物车页面显示
展示购物车中的商品列表和总价:
function displayCart() {
$total = 0;
if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $productId => $quantity) {
$product = $db->query("SELECT * FROM products WHERE id = $productId")->fetch_assoc();
$subtotal = $product['price'] * $quantity;
$total += $subtotal;
echo "<div class='cart-item'>
<h3>{$product['name']}</h3>
<p>Price: \${$product['price']}</p>
<p>Quantity: $quantity</p>
<p>Subtotal: \$$subtotal</p>
<a href='remove.php?id=$productId'>Remove</a>
</div>";
}
echo "<h3>Total: \$$total</h3>";
} else {
echo "Your cart is empty";
}
}
购物车功能扩展
实现数量修改和清空购物车功能:

// 更新商品数量
function updateQuantity($productId, $newQuantity) {
if ($newQuantity <= 0) {
removeFromCart($productId);
} else {
$_SESSION['cart'][$productId] = $newQuantity;
}
}
// 清空购物车
function emptyCart() {
$_SESSION['cart'] = array();
}
安全注意事项
处理用户输入时进行验证和过滤:
// 安全添加商品
function safeAddToCart() {
$productId = filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
$quantity = filter_input(INPUT_GET, 'quantity', FILTER_VALIDATE_INT);
if ($productId && $quantity) {
addToCart($productId, $quantity);
}
}
AJAX实现
使用jQuery实现无刷新购物车操作:
$('.add-to-cart').click(function() {
var productId = $(this).data('id');
$.post('add_to_cart.php', {product_id: productId}, function(data) {
$('#cart-count').text(data.cartCount);
}, 'json');
});






