php 实现购物车
PHP 实现购物车功能
购物车功能是电子商务网站的核心部分,可以通过 PHP 和 Session 或数据库来实现。以下是两种常见的实现方式:
使用 Session 存储购物车数据
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) {
if ($quantity > 0) {
$_SESSION['cart'][$product_id] = $quantity;
} else {
unset($_SESSION['cart'][$product_id]);
}
}
}
使用数据库存储购物车数据
对于需要持久化或用户登录后才能使用的购物车,可以将数据存储在数据库中。
// 数据库连接
$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("SELECT * FROM cart WHERE user_id = ? AND product_id = ?");
$stmt->execute([$user_id, $product_id]);
$item = $stmt->fetch();
if ($item) {
// 更新数量
$new_quantity = $item['quantity'] + $quantity;
$stmt = $db->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
$stmt->execute([$new_quantity, $item['id']]);
} else {
// 新增记录
$stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
$stmt->execute([$user_id, $product_id, $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 = ?
");
$stmt->execute([$user_id]);
return $stmt->fetchAll();
}
购物车页面显示
// 显示购物车内容
$cart_items = isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
foreach ($cart_items as $product_id => $quantity) {
// 获取商品信息
$product = getProductById($product_id);
echo '<div class="cart-item">';
echo '<h4>' . $product['name'] . '</h4>';
echo '<p>价格: $' . $product['price'] . '</p>';
echo '<form method="post">';
echo '<input type="number" name="quantity['.$product_id.']" value="'.$quantity.'">';
echo '<button type="submit" name="update_cart">更新</button>';
echo '<a href="?remove='.$product_id.'">移除</a>';
echo '</form>';
echo '</div>';
}
// 计算总价
function calculateTotal($cart_items) {
$total = 0;
foreach ($cart_items as $product_id => $quantity) {
$product = getProductById($product_id);
$total += $product['price'] * $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 DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
安全注意事项
- 对用户输入进行验证和过滤
- 使用预处理语句防止SQL注入
- 对敏感操作进行CSRF保护
- 对数量进行限制防止负数或过大值
以上代码提供了购物车的基本功能实现,可以根据实际需求进行扩展和优化。






