使用不同选项将同一商品添加到购物车中



我正在开发一个PHP购物车,我有3种产品,用户可以选择数量和黄油类型。正在将具有相同id的项目添加到购物车中,该id是数据库中的产品id。

我如何用不同的黄油选项将同一个项目添加到购物车中,这样我就可以对添加的项目使用不同的id/索引,因为在结账页面中,当我尝试删除一个项目时,会有多个项目因为id问题而被删除。我希望你能指导我这样做。这是我的购物车代码,

if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"])) 
{

$item_array_id = array_column($_SESSION["shopping_cart"], "item_id"); 
$item_array_butter = array_column($_SESSION["shopping_cart"], "butter_type");
if(isset($_POST["butter_type"]))
{
$butter_type = $_POST["butter_type"];
}
else
{
$butter_type = '';
}
if(in_array($_GET["id"], $item_array_id) && in_array($butter_type, $item_array_butter))
{
//increment qty by 1
$_SESSION["shopping_cart"][0]['item_quantity']++;
}
else if(in_array($_GET["id"], $item_array_id) && !in_array($butter_type, $item_array_butter))
{
$item = array("item_id"=>$_GET["id"],
"item_name"=>$_POST["hidden_name"],
"item_price"=> $_POST["hidden_price"],
"subtotal_price"=>$_POST["hidden_price"]*$_POST["quantity"],
"item_quantity"=>$_POST["quantity"],
"butter_type"=>$butter_type
);
array_push($_SESSION["shopping_cart"],$item); // Items added to cart
}
else
{
$item = array("item_id"=>$_GET["id"],
"item_name"=>$_POST["hidden_name"],
"item_price"=> $_POST["hidden_price"],
"subtotal_price"=>$_POST["hidden_price"]*$_POST["quantity"],
"item_quantity"=>$_POST["quantity"],
"butter_type"=>$butter_type
);
array_push($_SESSION["shopping_cart"],$item); // Items added to cart
}
}
else
{   
$_SESSION["shopping_cart"] = array();
if(isset($_POST["butter_type"]))
{
$butter_type = $_POST["butter_type"];
}
else
{
$butter_type = '';
}
$item = array("item_id"=>$_GET["id"],
"item_name"=>$_POST["hidden_name"],
"item_price"=> $_POST["hidden_price"],
"subtotal_price"=>$_POST["hidden_price"]*$_POST["quantity"],
"item_quantity"=>$_POST["quantity"],
"butter_type"=>$butter_type
);
array_push($_SESSION["shopping_cart"],$item); // Items added to cart
}
}

这是要添加到购物车的html表单:

<form method="post" action="index.php?action=add&id=<?php echo $mainrow["id"]; ?>">
<input type="submit" name="add_to_cart" id="add_to_cart" value="Add to Cart" />
</form

一个简单的解决方案是通过;id";以及";butter_type";在您的表单中都有值。

<form method="post" action="index.php?action=add&id=<?php echo $mainrow["id"]; ?>&butter_type=<?php echo $butterType ?>">

然后,在后端,当您存储项目时,而不是存储";id";创建一个组合键并将其保持为";id";。

$item = array("item_id"=> $_GET["id"].'_'.$_GET['butter_type']...

以这种方式,项目由项目的";id";以及它的";butter_type";

当您从购物车中取出商品时;id";,您应该删除具有以上组合键的会话项。

然后,当您结账时,您可以使用爆炸命令来获取项目id和黄油类型。

我已经解决了将"product_id"变量添加到购物车数组中的问题,并且我使用了会话变量计数器作为值,因此购物车中的所有项目都有一个唯一的id,并且能够在没有任何错误的情况下更新和删除项目。感谢您的帮助

最新更新