购物车功能是电子商务网站的主要功能模块之一,以下分别以session和cookie方式实现购物车功能 。
一 SESSION方式购物车
购物车功能是一个常见的网站功能,允许用户将自己喜欢的商品添加到购物车中以便后续购买。在PHP中,我们可以使用session来实现购物车功能。
首先,我们需要创建一个购物车页面,显示用户添加的商品以及相关操作(如删除商品、修改数量等)。这个页面可以是一个HTML表单,其中的每个商品都有一个对应的删除按钮和数量输入框。
在用户点击添加商品按钮时,我们可以将商品信息(如商品ID、名称、价格等)存储在一个数组中,并将该数组存储在session中。这个数组就代表了用户的购物车。
下面是一个使用session实现购物车功能的示例代码:
<?php
session_start();
// 添加商品到购物车
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_to_cart'])) {
$product_id = $_POST['product_id'];
$product_name = $_POST['product_name'];
$product_price = $_POST['product_price'];
$quantity = $_POST['quantity'];
$cart_item = array(
'id' => $product_id,
'name' => $product_name,
'price' => $product_price,
'quantity' => $quantity
);
// 检查购物车是否已创建
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// 将商品添加到购物车
$_SESSION['cart'][] = $cart_item;
// 重定向到购物车页面
header('Location: cart.php');
exit;
}
// 从购物车中删除商品
if (isset($_GET['remove_item'])) {
$item_index = $_GET['remove_item'];
if (isset($_SESSION['cart'][$item_index])) {
unset($_SESSION['cart'][$item_index]);
$_SESSION['cart'] = array_values($_SESSION['cart']);
}
// 重定向到购物车页面
header('Location: