php实现简单购物车
实现购物车的基本功能
购物车需要实现添加商品、删除商品、更新数量、计算总价等功能。使用PHP结合Session可以快速实现一个简单的购物车系统。
创建购物车类
创建一个Cart类来封装购物车的主要逻辑:

class Cart {
public function __construct() {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
}
public function addItem($id, $name, $price, $quantity = 1) {
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = [
'name' => $name,
'price' => $price,
'quantity' => $quantity
];
}
}
public function removeItem($id) {
unset($_SESSION['cart'][$id]);
}
public function updateQuantity($id, $quantity) {
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id]['quantity'] = $quantity;
}
}
public function getTotal() {
$total = 0;
foreach ($_SESSION['cart'] as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
public function getItems() {
return $_SESSION['cart'];
}
public function clear() {
$_SESSION['cart'] = [];
}
}
使用购物车
在页面中使用购物车功能:

session_start();
$cart = new Cart();
// 添加商品
$cart->addItem(1, 'iPhone', 999, 2);
$cart->addItem(2, 'MacBook', 1999, 1);
// 更新数量
$cart->updateQuantity(1, 3);
// 删除商品
$cart->removeItem(2);
// 获取总价
$total = $cart->getTotal();
// 获取所有商品
$items = $cart->getItems();
// 清空购物车
$cart->clear();
显示购物车内容
创建一个页面来显示购物车内容:
<table>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<?php foreach ($items as $id => $item): ?>
<tr>
<td><?php echo $item['name']; ?></td>
<td><?php echo $item['price']; ?></td>
<td><?php echo $item['quantity']; ?></td>
<td><?php echo $item['price'] * $item['quantity']; ?></td>
<td>
<a href="remove.php?id=<?php echo $id; ?>">删除</a>
</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan="3">总计</td>
<td><?php echo $total; ?></td>
</tr>
</table>
持久化存储
如果需要将购物车数据保存到数据库,可以在用户登录时将Session中的数据同步到数据库:
// 用户登录时从数据库加载购物车
if (isset($_SESSION['user_id'])) {
$userId = $_SESSION['user_id'];
// 从数据库查询购物车数据
// 并合并到Session中
}
// 用户退出时保存购物车到数据库
if (isset($_SESSION['user_id'])) {
$userId = $_SESSION['user_id'];
// 将Session中的购物车数据保存到数据库
}
注意事项
- 确保在每个使用购物车的页面都调用了
session_start() - 对用户输入进行验证,防止XSS攻击
- 考虑添加商品库存检查功能
- 对于大型电商系统,建议使用数据库存储购物车数据






