php购物车的实现
PHP 购物车实现方法
数据库设计
创建必要的数据库表存储商品和购物车信息。商品表(products)包含商品ID、名称、价格等字段;购物车表(cart)包含用户ID、商品ID、数量等字段。
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
price DECIMAL(10,2),
description TEXT
);
CREATE TABLE cart (
user_id INT,
product_id INT,
quantity INT,
PRIMARY KEY (user_id, product_id)
);
会话存储实现
使用PHP的$_SESSION超全局变量存储临时购物车数据,适合未登录用户。
session_start();
function addToCart($productId, $quantity) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
$_SESSION['cart'][$productId] = ($_SESSION['cart'][$productId] ?? 0) + $quantity;
}
数据库存储实现
对已登录用户,将购物车数据存入数据库。

function addToCartDB($userId, $productId, $quantity) {
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
$stmt = $pdo->prepare('INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)');
$stmt->execute([$userId, $productId, $quantity]);
}
显示购物车内容
从会话或数据库获取购物车数据并显示。
function displayCart() {
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $productId => $quantity) {
$product = getProductById($productId);
echo "{$product['name']} - {$product['price']} x $quantity<br>";
}
}
}
更新和删除商品
提供修改商品数量和删除商品的功能。

function updateCartItem($productId, $quantity) {
if ($quantity <= 0) {
unset($_SESSION['cart'][$productId]);
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
function removeFromCart($productId) {
unset($_SESSION['cart'][$productId]);
}
计算总价
遍历购物车计算商品总价。
function calculateTotal() {
$total = 0;
foreach ($_SESSION['cart'] as $productId => $quantity) {
$product = getProductById($productId);
$total += $product['price'] * $quantity;
}
return $total;
}
结账处理
将购物车数据转为订单并清空购物车。
function checkout($userId) {
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
$pdo->beginTransaction();
try {
$orderId = createOrder($userId);
foreach ($_SESSION['cart'] as $productId => $quantity) {
addOrderItem($orderId, $productId, $quantity);
}
unset($_SESSION['cart']);
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
}






