I'm creating a shopping cart. Two problems with the add and remove item features. When adding an item that's already in the cart, it doesn't overwrite the existing one, leading to two instances of the same item in the cart. Removing items only works for the topmost item on the list.
switch($_GET["action"])
{
case "add":
if(!empty($_POST["quantity"]))
{
$id=$_POST["id"];
$result = $mysqli->query("SELECT * FROM menu WHERE itemid='$id'");
while($itembyId=$result->fetch_assoc())
{
$itemArray = array($id=>array('name'=>$_POST["name"],
'id'=>$id, 'quantity'=>$_POST["quantity"], 'details'=>$_POST["details"],
'price'=>$_POST["price"]));
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itembyId["itemid"],$_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $k => $v)
{
if($itembyId["itemid"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $k => $v)
{
if($_GET["id"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
That works for me! It's an option for increases the quantity...
<form action="xxxx" method="POST"><input type="hidden" name="type" value="update_suma" /><input type="hidden" name="id" value="'.$item["id"].'" /><input type="submit"value="+" /></form>
<pre>case "update_suma":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_POST["identidad"] == $_SESSION["cart_item"][$k]['id'])
$_SESSION["cart_item"][$k]["cantidad"]++;
}
}
break;</pre>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.