'update product quantity in cart php session
I develop a new ecommerce site using PHP. I manage cart related data to database and store that data in session. The issue is when I add a product if the product is not in cart it adds that but if a product already exists it doesn't update quantity. This is my code for reference. I use key as product id
$getUserTemp['products']=array();
$mode=mysqli_real_escape_string($conn,$_POST['mode']);
$productId=mysqli_real_escape_string($conn,$_POST['product_id']);
$quantity=mysqli_real_escape_string($conn,$_POST['quantity']);
$productData=getSingleProduct("SELECT id,name,
quantity as quantity_in_stock,
original_price,discounted_price
from `products`
where id=".$productId."");
$productData['quantity']=$quantity;
switch ($mode) {
case 'add-to-cart':
if(empty($getUserTemp['products'])){
$getUserTemp['products'][$productId]=$productData;
}else{
foreach ($getUserTemp['products'] as $key => $value) {
if($key == $productId){
$value['quantity']+=$quantity;
$value[$productId]=$value;
}else{
$getUserTemp['products'][$productId]=$productData;
}
}
}
mysqli_query($conn,"UPDATE `session_cart` set session_data='".json_encode($getUserTemp)."' where user_id='".$currentLoggedUserId."'");
print_r($getUserTemp);
break;
}
My array data:
Array
(
[user] => Array
(
[id] => 8
[profile_id] => 6
[user_name] => [email protected]
[role] => user
[password] => $2y$10$bL4LybXcOX6nkEgRAM6Jjerrz2czEZJLWv7W1MNg.vWscb39NEsx2
)
[products] => Array
(
[38] => Array
(
[id] => 38
[name] => HP
[quantity_in_stock] => 33
[original_price] => 50.00
[discounted_price] => 40.00
[quantity] => 1
)
[8] => Array
(
[id] => 8
[name] => ASUS VivoBook 15 (2021) Core i3 10th Gen - (8 GB/512 GB SSD/Windows 11 Home) X515JA-EJ362WS Thin and Light Laptop (15.6 inch, Transparent Silver, 1.80 kg, With MS Office)
[quantity_in_stock] => 20
[original_price] => 50.00
[discounted_price] => 40.00
[quantity] => 1
)
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
