php购物车实现
PHP 购物车实现方法
使用 Session 存储购物车数据
在 PHP 中,可以通过 $_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]);
}
}
// 更新购物车商品数量
function updateCartItem($productId, $quantity) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] = $quantity;
}
}
使用数据库存储购物车数据
对于需要持久化存储的购物车数据,可以使用数据库表来存储。通常需要创建 cart 和 cart_items 表。
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE cart_items (
id INT AUTO_INCREMENT PRIMARY KEY,
cart_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (cart_id) REFERENCES cart(id)
);
PHP 操作数据库购物车的示例代码:
// 添加商品到数据库购物车
function addToCartDB($userId, $productId, $quantity) {
$pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'username', 'password');
// 检查用户是否有购物车
$stmt = $pdo->prepare("SELECT id FROM cart WHERE user_id = ?");
$stmt->execute([$userId]);
$cart = $stmt->fetch();
if (!$cart) {
// 创建新购物车
$stmt = $pdo->prepare("INSERT INTO cart (user_id) VALUES (?)");
$stmt->execute([$userId]);
$cartId = $pdo->lastInsertId();
} else {
$cartId = $cart['id'];
}
// 检查商品是否已在购物车
$stmt = $pdo->prepare("SELECT id FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->execute([$cartId, $productId]);
$item = $stmt->fetch();
if ($item) {
// 更新数量
$stmt = $pdo->prepare("UPDATE cart_items SET quantity = quantity + ? WHERE id = ?");
$stmt->execute([$quantity, $item['id']]);
} else {
// 添加新商品
$stmt = $pdo->prepare("INSERT INTO cart_items (cart_id, product_id, quantity) VALUES (?, ?, ?)");
$stmt->execute([$cartId, $productId, $quantity]);
}
}
实现购物车功能的关键组件
商品展示页面
需要显示商品列表,每个商品有"加入购物车"按钮,触发上述的 addToCart 或 addToCartDB 函数。
购物车页面 显示当前购物车中的所有商品,允许修改数量或移除商品。可以使用表格展示购物车内容,每行商品附带数量输入框和删除按钮。
// 显示购物车内容
function displayCart() {
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
echo "购物车为空";
return;
}
echo "<table>";
echo "<tr><th>商品</th><th>单价</th><th>数量</th><th>小计</th><th>操作</th></tr>";
foreach ($_SESSION['cart'] as $productId => $quantity) {
$product = getProductDetails($productId); // 假设有获取商品详情的函数
$subtotal = $product['price'] * $quantity;
echo "<tr>";
echo "<td>{$product['name']}</td>";
echo "<td>{$product['price']}</td>";
echo "<td><input type='number' value='$quantity' min='1'></td>";
echo "<td>$subtotal</td>";
echo "<td><button onclick='removeItem($productId)'>删除</button></td>";
echo "</tr>";
}
echo "</table>";
}
结算功能 提供结算按钮,计算总价并跳转到结账页面。结账页面可以收集配送信息并处理支付。
// 计算购物车总价
function calculateTotal() {
$total = 0;
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $productId => $quantity) {
$product = getProductDetails($productId);
$total += $product['price'] * $quantity;
}
}
return $total;
}
安全注意事项
- 始终对用户输入进行验证和过滤,防止 SQL 注入
- 使用预处理语句处理数据库操作
- 对敏感操作如结算进行 CSRF 保护
- 重要操作如支付使用 HTTPS 协议
扩展功能建议
- 添加优惠券和折扣功能
- 实现商品库存检查
- 添加购物车持久化(用户登录后保留)
- 实现愿望清单功能
- 添加商品评价系统







