1

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";

        }

    }
} 
3
  • check session_start(); or not ? Commented Oct 4, 2017 at 5:35
  • use session_start(); on top of the code just after <?php and you are good to go Commented Oct 4, 2017 at 5:35
  • session_start() is not the problem. session quantity is not setting what is prints Commented Oct 4, 2017 at 6:02

2 Answers 2

2
<?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";

        }

    }
} 
Sign up to request clarification or add additional context in comments.

1 Comment

adding session_start() shows error Notice: A session had already been started - ignoring session_start()
0

I found the solution. It would be

$_SESSION['careat_cart'][$key]['quantity']+= $quantiy_added;

Instead of

$value['quantity'] += $quantiy_added;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.