php购物车实现流程
PHP购物车实现流程
数据库设计
创建必要的数据库表存储商品、用户和购物车信息。核心表包括:
products:存储商品ID、名称、价格、库存等users:用户账号信息cart:关联用户ID和商品ID,记录数量
CREATE TABLE cart (
cart_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
会话管理
使用PHP的$_SESSION跟踪用户购物车状态。初始化购物车数组存储商品数据:

session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
商品添加功能
通过表单提交将商品加入购物车,验证库存后更新会话数据:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
// 检查库存
$stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
$stmt->execute([$product_id]);
$stock = $stmt->fetchColumn();
if ($quantity <= $stock) {
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
}
购物车显示
遍历会话中的购物车数据,联合查询商品详情:

$cart_items = array();
$total = 0;
if (!empty($_SESSION['cart'])) {
$placeholders = str_repeat('?,', count($_SESSION['cart']) - 1) . '?';
$stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
$stmt->execute(array_keys($_SESSION['cart']));
while ($row = $stmt->fetch()) {
$quantity = $_SESSION['cart'][$row['id']];
$subtotal = $row['price'] * $quantity;
$total += $subtotal;
$cart_items[] = array(
'product' => $row,
'quantity' => $quantity,
'subtotal' => $subtotal
);
}
}
更新与删除
实现购物车项目的动态修改,包括数量调整和移除:
// 更新数量
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]);
}
}
}
// 移除商品
if (isset($_GET['remove'])) {
unset($_SESSION['cart'][$_GET['remove']]);
}
结算流程
验证购物车状态后生成订单,减少库存:
if (isset($_POST['checkout'])) {
try {
$pdo->beginTransaction();
// 创建订单记录
$stmt = $pdo->prepare("INSERT INTO orders (user_id, total) VALUES (?, ?)");
$stmt->execute([$_SESSION['user_id'], $total]);
$order_id = $pdo->lastInsertId();
// 添加订单明细
$stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price)
VALUES (?, ?, ?, ?)");
foreach ($cart_items as $item) {
$stmt->execute([
$order_id,
$item['product']['id'],
$item['quantity'],
$item['product']['price']
]);
// 更新库存
$pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?")
->execute([$item['quantity'], $item['product']['id']]);
}
$pdo->commit();
unset($_SESSION['cart']); // 清空购物车
} catch (Exception $e) {
$pdo->rollBack();
}
}
安全注意事项
- 对所有用户输入使用预处理语句防止SQL注入
- 验证会话中的用户身份
- 关键操作如库存修改需使用事务处理
- 价格计算应在服务端完成,避免客户端篡改
扩展功能建议
- 实现优惠券系统
- 添加商品图片预览
- 开发AJAX无刷新操作
- 集成支付网关接口
- 增加购物车过期时间设置






