php实现购物车功能
实现购物车功能的基本思路
购物车功能通常涉及商品添加、删除、数量修改、计算总价等操作。PHP可以通过会话(Session)或数据库存储购物车数据。
使用Session存储购物车数据
初始化购物车Session:
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($products) {
$total = 0;
foreach ($_SESSION['cart'] as $product_id => $quantity) {
if (isset($products[$product_id])) {
$total += $products[$product_id]['price'] * $quantity;
}
}
return $total;
}
使用数据库存储购物车数据
创建购物车表:

CREATE TABLE cart (
cart_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
product_id INT,
quantity INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
添加商品到数据库购物车:
function addToCartDB($user_id, $product_id, $quantity = 1) {
$sql = "INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)";
// 使用预处理语句执行SQL
}
显示购物车内容
function displayCart($products) {
if (!empty($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $product_id => $quantity) {
if (isset($products[$product_id])) {
$product = $products[$product_id];
echo "商品: {$product['name']}, 单价: {$product['price']}, 数量: $quantity";
}
}
}
}
清空购物车
function clearCart() {
$_SESSION['cart'] = array();
}
安全注意事项
验证用户输入数据,防止SQL注入:
$product_id = filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
if ($product_id === false || $product_id === null) {
// 处理无效输入
}
对于敏感操作如删除或更新,应添加CSRF保护:
// 生成并验证CSRF令牌
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('非法请求');
}






