Reputation: 11
im now working in a cart where all products saved in a session variable. So if the same product exists in the cart it will just increase the quantity. But it looks like working when i echo out the variable but when i print the session variable it remain same. here is my code
<?php
require_once("inc/init.php");
$product_id = htmlentities($_POST['product_id'], ENT_QUOTES);
$quantiy_added = htmlentities($_POST['quantiy_added'], ENT_QUOTES);
$op = htmlentities($_POST['op'], ENT_QUOTES);
$Cart = new Cart();
//var_dump($Cart);
global $mysqli;
if ($op == "add-item") {
if (isset($_SESSION['careat_cart'])) { //if same item exists
foreach ($_SESSION['careat_cart'] as $key => $value) {
if ($product_id == $value['id']) {
$value['quantity'] += $quantiy_added;
echo $value['quantity'];
} else echo "new item";
}
}
}
Upvotes: 1
Views: 107
Reputation: 11
I found the solution. It would be
$_SESSION['careat_cart'][$key]['quantity']+= $quantiy_added;
Instead of
$value['quantity'] += $quantiy_added;
Upvotes: 0
Reputation: 1477
<?php
session_start();
require_once("inc/init.php");
$product_id = htmlentities($_POST['product_id'], ENT_QUOTES);
$quantiy_added = htmlentities($_POST['quantiy_added'], ENT_QUOTES);
$op = htmlentities($_POST['op'], ENT_QUOTES);
$Cart = new Cart();
//var_dump($Cart);
global $mysqli;
if ($op == "add-item") {
if (isset($_SESSION['careat_cart'])) { //if same item exists
foreach ($_SESSION['careat_cart'] as $key => $value) {
if ($product_id == $value['id']) {
$value['quantity'] += $quantiy_added;
echo $value['quantity'];
} else echo "new item";
}
}
}
Upvotes: 2