Reputation: 929
I have implemented simple shopping cart using php.I can add product in cart and it adds to array.i Get my product id on url,when i click add to cart button based on thar url id i fetch product data from database and add to session array,but my problem is when i add same product i get new entry in session and the instead of updating quantity of that product. So what code i write to update the cart quantity if produt_id already there.?
This is print_r array value using $_SESSION['cart']
.
[cart] => Array
(
[0] => Array
(
[product-id] => 1
[item] => mango
[unitprice] => 20
[quantity] => 1
)
[1] => Array
(
[product-id] =>2
[item] => chickoo
[unitprice] => 20
[quantity] => 1
)
)
Upvotes: 1
Views: 4953
Reputation: 9299
Sounds like you need to make sure the product_id
isn't already in your session array. Try the following
$found = false;
foreach($_SESSION['cart'] as $product)
{
if($_REQUEST['product_id'] == $product['product_id']) {
$found = true;
break;
}
}
if($found)
{
$_SESSION['cart'][$_REQUEST['product_id']]['quantity'] += 1;
} else {
// go get new product and add to $_SESSION['cart']
}
Upvotes: 1