php购物车实现代码
基本购物车实现
PHP购物车可以通过Session或数据库存储商品信息。以下是一个基于Session的简单实现:
<?php
session_start();
// 添加商品到购物车
if (isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
// 从购物车移除商品
if (isset($_GET['remove'])) {
$product_id = $_GET['remove'];
unset($_SESSION['cart'][$product_id]);
}
// 更新购物车数量
if (isset($_POST['update_cart'])) {
foreach ($_POST['quantity'] as $product_id => $quantity) {
if ($quantity <= 0) {
unset($_SESSION['cart'][$product_id]);
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
}
?>
购物车显示页面
<?php
session_start();
if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
echo "购物车为空";
exit;
}
// 假设$products是从数据库获取的商品信息
$products = [
1 => ['name' => '商品A', 'price' => 100],
2 => ['name' => '商品B', 'price' => 200]
];
?>
<form method="post" action="cart.php">
<table>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<?php
$total = 0;
foreach ($_SESSION['cart'] as $product_id => $quantity):
$product = $products[$product_id];
$subtotal = $product['price'] * $quantity;
$total += $subtotal;
?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['price']; ?>元</td>
<td><input type="number" name="quantity[<?php echo $product_id; ?>]" value="<?php echo $quantity; ?>"></td>
<td><?php echo $subtotal; ?>元</td>
<td><a href="cart.php?remove=<?php echo $product_id; ?>">删除</a></td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan="3">总计</td>
<td><?php echo $total; ?>元</td>
<td></td>
</tr>
</table>
<input type="submit" name="update_cart" value="更新购物车">
</form>
数据库存储方案
对于需要持久化存储的购物车,可以使用数据库方案:
// 数据库连接
$db = new PDO('mysql:host=localhost;dbname=shop', 'username', 'password');
// 添加商品到购物车
function addToCart($user_id, $product_id, $quantity) {
global $db;
$stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE quantity = quantity + ?");
$stmt->execute([$user_id, $product_id, $quantity, $quantity]);
}
// 获取用户购物车
function getCart($user_id) {
global $db;
$stmt = $db->prepare("SELECT p.id, p.name, p.price, c.quantity
FROM cart c
JOIN products p ON c.product_id = p.id
WHERE c.user_id = ?");
$stmt->execute([$user_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
安全注意事项
购物车实现需要考虑以下安全措施:
- 对用户输入进行验证和过滤
- 防止SQL注入攻击
- 对商品ID进行验证,确保是有效商品
- 对数量进行限制,防止负数或过大数值
// 安全过滤示例
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$quantity = filter_input(INPUT_POST, 'quantity', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 99]
]);
if (!$product_id || !$quantity) {
die('无效输入');
}
以上代码提供了PHP购物车的基本实现方案,可以根据实际需求进行扩展和完善。







