php - 我无法将多个产品添加到我的 PHP 购物车
问题描述
我想使用 PHP 将带有产品信息的多个产品添加到购物车页面,但我不能。我的第一个产品已添加,但随后无法正常工作。
我的代码是:
<?php
session_start();
// session_destroy();
// Add to Cart
if (isset($_POST["add_to_cart"])) {
$name = $_POST["name"];
$price = $_POST["price"];
$quantity = $_POST["quantity"];
$stock = $_POST["stock"];
if ($stock >= $quantity) {
if (isset($_SESSION["cart"])) {
$cart_item = array(
'p_name' => $name,
'p_price' => $price,
'p_quantity' => $quantity,
'p_stock' => $stock,
);
$new_item = array_merge($_SESSION["cart"], $cart_item);
$_SESSION["cart"] = $new_item;
print_r($_SESSION["cart"]);
} else {
$cart_item = array(
'p_name' => $name,
'p_price' => $price,
'p_quantity' => $quantity,
'p_stock' => $stock,
);
$_SESSION["cart"] = $cart_item;
print_r($_SESSION["cart"]);
}
} else {
}
} else {
print_r($_SESSION["cart"]);
}
?>
解决方案
我已经更改了代码以增加可读性和功能。我所做的主要事情是确定没有创建多维数组,这是问题的根源。
$cart_item = array(
'p_name' => $name,
'p_price' => $price,
'p_quantity' => $quantity,
'p_stock' => $stock,
);
$_SESSION["cart"] = $cart_item;
那只会给你一个单一的产品。我已经改变了它,所以它将是一个贯穿始终并且可以包含许多产品的阵列。
<?php
session_start();
// session_destroy();
// Add to Cart
if (isset($_POST["add_to_cart"])) {
$name = $_POST["name"];
$price = $_POST["price"];
$quantity = $_POST["quantity"];
$stock = $_POST["stock"];
// Pull the array (if it exists into a variable)
$cart = $_SESSION['cart'];
if (!isset($cart)) {
// Define the cart as an array
$cart = [];
}
if ($stock >= $quantity) {
// Push the product into the array of cart items
$cart[] = [
'p_name' => $name,
'p_price' => $price,
'p_quantity' => $quantity,
'p_stock' => $stock,
];
// Set the cart to the $_SESSION
$_SESSION["cart"] = $cart;
print_r($_SESSION["cart"]);
} else {
// Should probably do something here
echo "We are out of stock.";
}
} else {
if (isset($_SESSION['cart'])) {
print_r($_SESSION["cart"]);
}
}
推荐阅读
- openvpn - OpenVPN路由窗口访问windows客户端的局域网
- rust - 如何指定在某些特征边界下满足给定第一个特征的任何类型也必须隐式满足第二个特征?
- python - 是否可以防止 VISUAL STUDIO 在 DEBUG CONSOLE 中自动添加新行?
- wso2 - BPMN 集成?
- r - 如何在 valueBox (flaxdashboard R) 中插入图标?
- javascript - HTML5 视频:无法读取未定义的属性“toLowerCase”
- python-3.x - 如何修改 PostgreSQL psycopg 以接受变量而不是值
- spring - 使用 Spring Boot 在匿名 url 上接收授权标头
- apache-spark - Spark结构化流式连接不起作用
- elixir - 如何在另一个模块中使用结构