php实现简单购物车
PHP 实现简单购物车
创建数据库表
购物车功能通常需要存储商品信息和用户选择的商品。创建一个简单的数据库表结构:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT
);
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
session_id VARCHAR(255) NOT NULL,
FOREIGN KEY (product_id) REFERENCES products(id)
);
添加商品到购物车
使用 PHP 将商品添加到购物车,通常通过会话(Session)或数据库存储购物车信息。
<?php
session_start();
function addToCart($productId, $quantity = 1) {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId] += $quantity;
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
// 示例:添加商品 ID 为 1 的商品到购物车
addToCart(1, 2);
?>
显示购物车内容
从会话或数据库中读取购物车内容并显示。

<?php
session_start();
function getCartItems() {
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
return [];
}
$cartItems = [];
foreach ($_SESSION['cart'] as $productId => $quantity) {
// 假设从数据库获取商品信息
$product = getProductById($productId);
if ($product) {
$cartItems[] = [
'product' => $product,
'quantity' => $quantity
];
}
}
return $cartItems;
}
function getProductById($id) {
// 模拟从数据库获取商品信息
$products = [
1 => ['id' => 1, 'name' => '商品1', 'price' => 10.99],
2 => ['id' => 2, 'name' => '商品2', 'price' => 20.50]
];
return $products[$id] ?? null;
}
$cartItems = getCartItems();
?>
<ul>
<?php foreach ($cartItems as $item): ?>
<li>
<?php echo $item['product']['name']; ?> -
<?php echo $item['quantity']; ?> ×
<?php echo $item['product']['price']; ?> =
<?php echo $item['quantity'] * $item['product']['price']; ?>
</li>
<?php endforeach; ?>
</ul>
更新购物车数量
允许用户修改购物车中商品的数量。
<?php
session_start();
function updateCartItem($productId, $quantity) {
if (isset($_SESSION['cart'][$productId])) {
if ($quantity <= 0) {
unset($_SESSION['cart'][$productId]);
} else {
$_SESSION['cart'][$productId] = $quantity;
}
}
}
// 示例:更新商品 ID 为 1 的数量为 3
updateCartItem(1, 3);
?>
移除购物车商品
提供从购物车中移除商品的功能。

<?php
session_start();
function removeFromCart($productId) {
if (isset($_SESSION['cart'][$productId])) {
unset($_SESSION['cart'][$productId]);
}
}
// 示例:移除商品 ID 为 1 的商品
removeFromCart(1);
?>
计算购物车总价
计算购物车中所有商品的总价格。
<?php
session_start();
function calculateTotal() {
$total = 0;
$cartItems = getCartItems();
foreach ($cartItems as $item) {
$total += $item['product']['price'] * $item['quantity'];
}
return $total;
}
$total = calculateTotal();
echo "总价: " . $total;
?>
清空购物车
提供清空购物车的功能。
<?php
session_start();
function clearCart() {
$_SESSION['cart'] = [];
}
// 示例:清空购物车
clearCart();
?>
使用数据库存储购物车
如果需要持久化存储购物车数据,可以将购物车信息保存到数据库中。
<?php
function addToCartDB($productId, $sessionId, $quantity = 1) {
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO cart (product_id, session_id, quantity) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + ?");
$stmt->execute([$productId, $sessionId, $quantity, $quantity]);
}
// 示例:添加商品到数据库购物车
addToCartDB(1, session_id(), 2);
?>
安全注意事项
- 验证用户输入,防止 SQL 注入。
- 使用预处理语句处理数据库操作。
- 对会话 ID 进行安全处理,防止会话劫持。






