购物车实现 php
实现购物车的基本功能
购物车是电商网站的核心功能之一,允许用户将商品添加到临时存储区域,后续进行结算。使用PHP实现购物车通常涉及会话管理、数据库交互和前端展示。
使用会话存储购物车数据
PHP的$_SESSION超全局变量适合存储临时购物车数据,无需立即写入数据库。初始化会话并创建购物车数组:
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
添加商品到购物车时,检查是否已存在并更新数量:
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
从数据库获取商品信息
通常需要从数据库查询商品详情用于展示:

$cart_items = array();
if (!empty($_SESSION['cart'])) {
$ids = implode(',', array_keys($_SESSION['cart']));
$sql = "SELECT * FROM products WHERE id IN ($ids)";
// 执行查询并将结果存入$cart_items
}
展示购物车内容
结合HTML展示购物车商品列表,包括单价、数量和总价:
<table>
<tr>
<th>商品</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
<?php foreach ($cart_items as $item): ?>
<tr>
<td><?php echo htmlspecialchars($item['name']); ?></td>
<td><?php echo $item['price']; ?></td>
<td>
<input type="number" name="quantity[<?php echo $item['id']; ?>]"
value="<?php echo $_SESSION['cart'][$item['id']]; ?>">
</td>
<td><?php echo $item['price'] * $_SESSION['cart'][$item['id']]; ?></td>
</tr>
<?php endforeach; ?>
</table>
更新购物车数量
处理表单提交来更新商品数量:

if (isset($_POST['update_cart'])) {
foreach ($_POST['quantity'] as $id => $qty) {
if ($qty > 0) {
$_SESSION['cart'][$id] = $qty;
} else {
unset($_SESSION['cart'][$id]);
}
}
}
移除购物车商品
提供删除按钮移除特定商品:
if (isset($_GET['remove'])) {
$remove_id = $_GET['remove'];
if (isset($_SESSION['cart'][$remove_id])) {
unset($_SESSION['cart'][$remove_id]);
}
}
计算购物车总价
遍历购物车商品计算总金额:
$total = 0;
foreach ($cart_items as $item) {
$total += $item['price'] * $_SESSION['cart'][$item['id']];
}
持久化购物车数据
对于已登录用户,可将购物车数据存入数据库:
if (isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
$cart_data = serialize($_SESSION['cart']);
// 执行INSERT或UPDATE操作将$cart_data存入users表的cart字段
}
安全注意事项
- 对所有用户输入使用
htmlspecialchars()防止XSS攻击 - 使用预处理语句防止SQL注入
- 验证商品ID是否存在数据库中
- 限制数量输入范围为合理数值
这种实现方式提供了购物车的基本功能,可根据需求扩展优惠券、运费计算等高级功能。对于大型电商平台,建议考虑使用专门的购物车类或框架来管理更复杂的业务逻辑。






