I want to update the quantity of an item in the cart
These are the actions:
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["item_code"]=>array('name'=>$productByCode[0]["item_name"], 'code'=>$productByCode[0]["item_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["item_price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["item_code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["item_code"] == $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["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
This is the cart code:
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["quantity"]; ?></td>
<td><?php echo "₹".$item["price"]; ?></td>
<td><a id="remove" href="index.php?action=remove&code=<?php echo $item["code"]; ?>"><span class="fa fa-times fa-lg" style="color:red;"></span></a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
I need something like when click on update button so it can take the value and update the session array of particular product quantity Please help me out...
This is a pretty basic example, but you should make a function per action so you can more easily port the cart. Also, I am not sure why you have a
$_GET
in theswitch
and a$_POST
in thecase()
:To use: