php购物车实现代码


PHP购物车实现代码
以下是一个简单的PHP购物车实现示例,包含添加商品、删除商品、更新数量和计算总价等功能。
创建购物车类
class ShoppingCart {
private $items = [];
// 添加商品到购物车
public function addItem($productId, $productName, $price, $quantity = 1) {
if (isset($this->items[$productId])) {
$this->items[$productId]['quantity'] += $quantity;
} else {
$this->items[$productId] = [
'name' => $productName,
'price' => $price,
'quantity' => $quantity
];
}
}
// 从购物车移除商品
public function removeItem($productId) {
if (isset($this->items[$productId])) {
unset($this->items[$productId]);
}
}
// 更新商品数量
public function updateQuantity($productId, $quantity) {
if (isset($this->items[$productId]) && $quantity > 0) {
$this->items[$productId]['quantity'] = $quantity;
}
}
// 获取购物车所有商品
public function getItems() {
return $this->items;
}
// 计算购物车总价
public function getTotalPrice() {
$total = 0;
foreach ($this->items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
// 清空购物车
public function clearCart() {
$this->items = [];
}
}
使用购物车类
// 初始化购物车
$cart = new ShoppingCart();
// 添加商品
$cart->addItem(1, 'iPhone', 999.99, 2);
$cart->addItem(2, 'MacBook', 1499.99, 1);
// 更新数量
$cart->updateQuantity(1, 3);
// 获取购物车内容
$items = $cart->getItems();
// 计算总价
$total = $cart->getTotalPrice();
// 移除商品
$cart->removeItem(2);
// 清空购物车
$cart->clearCart();
结合Session实现持久化
// 开始session
session_start();
// 初始化购物车
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = new ShoppingCart();
}
$cart = $_SESSION['cart'];
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['add'])) {
$cart->addItem($_POST['product_id'], $_POST['product_name'], $_POST['price'], $_POST['quantity']);
}
elseif (isset($_POST['remove'])) {
$cart->removeItem($_POST['product_id']);
}
elseif (isset($_POST['update'])) {
$cart->updateQuantity($_POST['product_id'], $_POST['quantity']);
}
}
前端显示购物车
<table>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<?php foreach ($cart->getItems() as $id => $item): ?>
<tr>
<td><?= htmlspecialchars($item['name']) ?></td>
<td>$<?= number_format($item['price'], 2) ?></td>
<td>
<form method="post">
<input type="number" name="quantity" value="<?= $item['quantity'] ?>">
<input type="hidden" name="product_id" value="<?= $id ?>">
<button type="submit" name="update">更新</button>
</form>
</td>
<td>$<?= number_format($item['price'] * $item['quantity'], 2) ?></td>
<td>
<form method="post">
<input type="hidden" name="product_id" value="<?= $id ?>">
<button type="submit" name="remove">删除</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan="3">总计</td>
<td>$<?= number_format($cart->getTotalPrice(), 2) ?></td>
<td></td>
</tr>
</table>
这个实现包含了购物车的基本功能,可以根据实际需求进行扩展,如添加商品图片、库存检查、折扣计算等功能。






