当前位置:首页 > 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>

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

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

相关文章

vue实现弹窗代码

vue实现弹窗代码

Vue 弹窗实现方法 方法一:使用组件与v-if控制显示 创建一个独立的弹窗组件(如Modal.vue),通过父组件的v-if或v-show控制显隐: <!-- Modal.vue --&g…

vue 实现git代码对比

vue 实现git代码对比

Vue 实现 Git 代码对比 在 Vue 中实现 Git 代码对比功能,可以通过集成现有的代码对比库或调用 Git 相关 API 来实现。以下是几种常见的方法: 使用 diff2html 库 di…

vue实现代码实例

vue实现代码实例

以下是一个基于 Vue 3 的完整代码实例,包含核心功能实现和常见开发场景的示例: 基础组件示例 <template> <div> <h1>{{ ti…

vue交错实现代码

vue交错实现代码

Vue 交错动画实现方法 使用 Vue 的 <transition-group> 组件结合 CSS 过渡可以实现交错动画效果。以下是一个典型实现方式: <template&…

打包好的react代码如何在本地跑

打包好的react代码如何在本地跑

运行打包后React项目的本地方法 安装serve工具 全局安装serve包,用于快速启动本地静态服务器。通过npm或yarn执行以下命令: npm install -g serve # 或 yar…

react实现批量新增代码

react实现批量新增代码

React 实现批量新增功能 批量新增功能通常涉及表单数据收集、状态管理和后端API交互。以下是实现步骤: 状态管理 使用React的useState或useReducer管理批量数据 const…