Reputation: 428
I am creating a basket and what I want is if an item that is already in the basket is added again, the quantity of the original item will be appended by 1.
Instead when I add an item that is already in the basket, a new item is added, and the quantity of this new item can be appended by clicking +1 on the original item.
basket.php
<?php
foreach ($_SESSION["basket"] as $basketItemArray) {
?>
<form role="form" action="includes/functions/create_shopping_cart.php" method="post">
<button type="submit" name="basket-button" class="btn btn-default" value="<?php echo $basketItemArray["item_id"]; ?>"><i class="fa fa-plus" aria-hidden="true"></i></button>
<? echo $basketItemArray["quantity"]; ?>
<button class="btn btn-default"><i class="fa fa-minus" aria-hidden="true"></i></button>
</form>
The above form sends the item_id through the value of the + button.
create_shopping_cart.php
$product_id = $_POST['basket-button'];
$sql = "SELECT * FROM menu WHERE product_id='".$product_id."'";
$result = $connection->query($sql);
$row = $result->fetch_assoc();
if (empty($_SESSION["basket"])) {
$_SESSION["basket"] = array(
array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );
} else {
// There is already a basket to append to
$current_basket = $_SESSION["basket"];
$found = false;
foreach($_SESSION['basket'] as $product)
{
if($product_id == $product['item_id']) {
$found = true;
break;
}
}
if($found)
{
$_SESSION['basket'][$product_id]['quantity'] ++;
} else {
$new_basket = array(
array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );
$_SESSION['basket'] = array_merge($current_basket, $new_basket);
}
}
Upvotes: 0
Views: 83
Reputation: 3925
You are not targeting/using the index of the products in basket. Try this:
$product_id = $_POST['basket-button'];
$sql = "SELECT * FROM menu WHERE product_id='".$product_id."'";
$result = $connection->query($sql);
$row = $result->fetch_assoc();
if (empty($_SESSION["basket"])) {
$_SESSION["basket"] = array(
array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );
} else {
// There is already a basket to append to
$current_basket = $_SESSION["basket"];
$found = false;
$id = '';
foreach($_SESSION['basket'] as $key=>$product)
{
if($product_id == $product['item_id']) {
$found = true;
$id = $key;
break;
}
}
if($found)
{
$_SESSION['basket'][$id]['quantity']++;
} else {
$new_basket = array(
array( "item_id"=>$row['product_id'], "item_name"=>$row['name'],"quantity"=>1 , "price"=>$row['price']) );
$_SESSION['basket'] = array_merge($current_basket, $new_basket);
}
}
Your code can be optimized some more but for now it is more important to get it to work correctly.
Upvotes: 1