当前位置:首页 > PHP

php购物车实现代码

2026-04-03 01:58:26PHP

php购物车实现代码

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>

这个实现包含了购物车的基本功能,可以根据实际需求进行扩展,如添加商品图片、库存检查、折扣计算等功能。

标签: 购物车代码
分享给朋友:

相关文章

php实现文件下载代码

php实现文件下载代码

实现文件下载的基本方法 使用PHP实现文件下载的核心是通过设置HTTP头部信息,强制浏览器触发下载行为而非直接显示文件内容。 $file_path = 'path/to/your/file.ext'…

vue实现代码

vue实现代码

以下是Vue实现常见功能的代码示例,涵盖基础语法、组件通信、状态管理等核心内容: 基础模板语法 <template> <div> <h1>{{ mes…

vue代码核心实现

vue代码核心实现

Vue 核心实现原理 Vue.js 的核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是关键实现要点: 响应式系统 通过 Object.defineProperty(Vue 2)…

vue代码怎么实现拼音

vue代码怎么实现拼音

实现拼音功能的方法 在Vue中实现拼音功能,可以通过拼音转换库将中文转换为拼音。以下是具体实现步骤: 安装拼音转换库 推荐使用pinyin或v-chinese2pinyin库。通过npm或yarn安…

vue路由实现代码

vue路由实现代码

Vue 路由实现代码 Vue Router 是 Vue.js 的官方路由库,用于构建单页面应用(SPA)。以下是 Vue Router 的基本实现代码示例: 安装 Vue Router 通过 npm…

vue 实现 代码编辑功能

vue 实现 代码编辑功能

实现代码编辑功能的基本思路 在Vue中实现代码编辑功能通常需要借助第三方库,例如Monaco Editor(VS Code使用的编辑器)或CodeMirror。以下是两种常见方案的实现方法。 使用M…