php实现简单购物车
PHP 实现简单购物车
创建数据库表结构
购物车功能通常需要数据库支持。创建一个简单的 cart 表:
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
使用 PDO 连接数据库:
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
添加商品到购物车
处理表单提交并将商品添加到购物车:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
$productId = $_POST['product_id'];
$quantity = $_POST['quantity'];
$userId = 1; // 假设用户ID为1,实际应用中应从会话获取
$stmt = $pdo->prepare("INSERT INTO cart (product_id, quantity, user_id) VALUES (?, ?, ?)");
$stmt->execute([$productId, $quantity, $userId]);
header("Location: cart.php");
exit;
}
显示购物车内容
查询并显示当前用户的购物车内容:
$userId = 1; // 假设用户ID为1
$stmt = $pdo->prepare("SELECT * FROM cart WHERE user_id = ?");
$stmt->execute([$userId]);
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($cartItems as $item) {
echo "Product ID: " . $item['product_id'] . "<br>";
echo "Quantity: " . $item['quantity'] . "<br><br>";
}
更新购物车商品数量
处理更新购物车商品数量的请求:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) {
$cartId = $_POST['cart_id'];
$newQuantity = $_POST['quantity'];
$stmt = $pdo->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
$stmt->execute([$newQuantity, $cartId]);
header("Location: cart.php");
exit;
}
从购物车移除商品
处理从购物车删除商品的请求:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_from_cart'])) {
$cartId = $_POST['cart_id'];
$stmt = $pdo->prepare("DELETE FROM cart WHERE id = ?");
$stmt->execute([$cartId]);
header("Location: cart.php");
exit;
}
计算购物车总价
计算购物车中所有商品的总价格:
$total = 0;
$stmt = $pdo->prepare("SELECT c.quantity, p.price FROM cart c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?");
$stmt->execute([$userId]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($items as $item) {
$total += $item['quantity'] * $item['price'];
}
echo "Total: $" . number_format($total, 2);
使用会话实现临时购物车
如果不使用数据库,可以使用 PHP 会话实现临时购物车:
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// 添加商品
if (isset($_POST['add_to_cart'])) {
$productId = $_POST['product_id'];
$quantity = $_POST['quantity'];
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] += $quantity;
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 显示购物车
foreach ($_SESSION['cart'] as $productId => $quantity) {
echo "Product ID: $productId, Quantity: $quantity<br>";
}
这个实现提供了基本的购物车功能,可以根据实际需求进行扩展和完善。






