一个简单商城购物车功能。它使用了PHP的会话(Session)来存储购物车数据通过调用不同的函数实现添加商品、移除商品更新商品数量以及清空购物车的功能


session_start();

// 初始化购物if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

// 添加商品到购物车
function addToCart($product_id, $quantity) {
    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 updateQuantity($product_id, $quantity) {
    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}

// 清空购物车
function clearCart() {
    $_SESSION['cart'] = array();
}

// 获取购物车中的商品列表
function getCart() {
    return $_SESSION['cart'];
}

原文地址:https://blog.csdn.net/weixin_39934453/article/details/134635361

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_25380.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注