Pergunta

i'm developing a shopping cart system and when i try to add a product for the first time it always give me an warning saying the following:

Notice: Undefined index: 2 in .../cart.php on line 9

The index: 2 is the id_product

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
        $product= $_POST['id_product'];
        $quantity= $_POST['qty'];
        $_SESSION['cart'][$product]+=$quantity;
    }

It's adding the values eitherway, but after i refresh the page that will appear on my foreach table. The values that i'm receiving are correct.

I'm defining the default values when after i log in on another page.

$_SESSION['car'][0] = 0;

Any suggestion?

Foi útil?

Solução

In the statement $_SESSION['cart'][$product]+=$quantity; You are using += and this is what causing the problem.

When you add the product for the first time it will throw error and afterwords work fine.

To solve this do something like this.

$quantity= $_POST['qty'];
if(!empty($_SESSION['cart'][$product])){
     $quantity = $quantity + $_SESSION['cart'][$product];
}
$_SESSION['cart'][$product] = $quantity;

Outras dicas

Hi you need to make your id_product a valid variable,

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
    $product= $_POST['id_product'];
    $quantity= $_POST['qty'];

    if(!isset($_SESSION['cart'][$product])) {
        $_SESSION['cart'][$product] = $quantity;
    } 
    else { 
        $_SESSION['cart'][$product]+=$quantity;
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top