当前位置:首页 > PHP

php购物车实现代码

2026-02-27 17:14:39PHP

PHP购物车实现代码

购物车功能是电子商务网站的核心部分,以下是一个简单的PHP购物车实现代码示例,包含添加商品、删除商品、更新数量和计算总价等功能。

数据库表结构

创建一个简单的products表和cart表:

php购物车实现代码

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    price DECIMAL(10, 2),
    description TEXT
);

CREATE TABLE cart (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT,
    quantity INT,
    session_id VARCHAR(100)
);

添加商品到购物车

<?php
session_start();
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

function addToCart($product_id, $quantity = 1) {
    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] += $quantity;
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}
?>

从购物车移除商品

function removeFromCart($product_id) {
    if (isset($_SESSION['cart'][$product_id])) {
        unset($_SESSION['cart'][$product_id]);
    }
}

更新购物车商品数量

function updateCartItem($product_id, $quantity) {
    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}

计算购物车总价

function calculateTotal() {
    $total = 0;
    $db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');

    foreach ($_SESSION['cart'] as $product_id => $quantity) {
        $stmt = $db->prepare("SELECT price FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();

        $total += $product['price'] * $quantity;
    }

    return $total;
}

显示购物车内容

function displayCart() {
    $db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');

    echo "<table border='1'>";
    echo "<tr><th>Product</th><th>Price</th><th>Quantity</th><th>Total</th><th>Action</th></tr>";

    foreach ($_SESSION['cart'] as $product_id => $quantity) {
        $stmt = $db->prepare("SELECT name, price FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();

        $item_total = $product['price'] * $quantity;

        echo "<tr>";
        echo "<td>{$product['name']}</td>";
        echo "<td>\${$product['price']}</td>";
        echo "<td><input type='number' value='{$quantity}' min='1' onchange='updateQuantity({$product_id}, this.value)'></td>";
        echo "<td>\${$item_total}</td>";
        echo "<td><button onclick='removeItem({$product_id})'>Remove</button></td>";
        echo "</tr>";
    }

    echo "</table>";
    echo "<p>Total: \$" . calculateTotal() . "</p>";
}

JavaScript辅助函数

function updateQuantity(product_id, quantity) {
    window.location.href = 'update_cart.php?product_id=' + product_id + '&quantity=' + quantity;
}

function removeItem(product_id) {
    window.location.href = 'remove_from_cart.php?product_id=' + product_id;
}

处理表单的PHP文件

创建add_to_cart.php:

php购物车实现代码

<?php
session_start();
include 'cart_functions.php';

if (isset($_GET['product_id'])) {
    addToCart($_GET['product_id'], $_GET['quantity'] ?? 1);
}

header('Location: products.php');

创建remove_from_cart.php:

<?php
session_start();
include 'cart_functions.php';

if (isset($_GET['product_id'])) {
    removeFromCart($_GET['product_id']);
}

header('Location: cart.php');

创建update_cart.php:

<?php
session_start();
include 'cart_functions.php';

if (isset($_GET['product_id']) && isset($_GET['quantity'])) {
    updateCartItem($_GET['product_id'], $_GET['quantity']);
}

header('Location: cart.php');

这个实现使用了PHP的Session来临时存储购物车数据,并与数据库交互获取商品详细信息。可以根据实际需求扩展功能,如添加用户认证、持久化存储购物车数据等。

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

相关文章

vue怎么实现文本代码实现

vue怎么实现文本代码实现

Vue 实现文本代码展示的方法 在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式: 使用 <pre> 和 <code> 标签 通过 HT…

vue论坛代码实现

vue论坛代码实现

Vue 论坛代码实现 项目初始化 使用 Vue CLI 或 Vite 创建一个新的 Vue 项目。推荐使用 Vue 3 和 Composition API。 npm create vue@lates…

vue 实现 代码编辑功能

vue 实现 代码编辑功能

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

react如何监控代码错误

react如何监控代码错误

监控 React 代码错误的常用方法 使用 Error Boundaries 捕获组件错误 Error Boundaries 是 React 提供的错误捕获机制,通过定义 componentDidCa…

如何建立运行react代码

如何建立运行react代码

安装 Node.js 和 npm React 项目需要 Node.js 环境来运行,同时 npm(Node Package Manager)用于管理依赖。从 Node.js 官网 下载并安装最新稳定版…

react中如何筛选购物车数据

react中如何筛选购物车数据

筛选购物车数据的实现方法 在React中筛选购物车数据通常涉及状态管理、过滤逻辑和渲染优化。以下是几种常见的实现方式: 使用状态管理存储购物车数据 购物车数据通常存储在组件的状态(如useState…