0

I can't figure out why I receive the error. After pressing the Add button the notice disappears at refresh.

<?php

    session_start();
    //session_destroy();
    $page ='index.php';

    mysql_connect('localhost','root','') or die(mysql_error());
    mysql_select_db('cart') or die(mysql_error());


     if (isset($_GET['add'])) {

        $_SESSION['cart_'.$_GET['add']] +'1';
        }

    function products() {

    $get = mysql_query('Select id, name, description, price from products where quantity > 0 order by id desc');

    if (mysql_num_rows($get) == 0 ) 
    {
    echo "There are no products to display";
    }
        while ($get_row = mysql_fetch_assoc($get)) {
            echo '<p>'.$get_row['name'].'<br/>'
                      .$get_row['description'].'<br/>'
                      .number_format($get_row['price'],2)
                      .' <a href="cart.php?add='.$get_row['id'].'">
                         Add
                         </a>
                 </p>';

            }
    }
    echo $_SESSION['cart_1']
?>

--------and index.php

<?php require 'cart.php' ?>
<html>
<head>
</head>
<body>

<?php products(); ?>

</body>
</html>

After executing index.php for the first time, I receive the error: Notice: Undefined index: cart_1 in E:\xamp\htdocs\ShopCart\cart.php on line 35

Andy G
  • 19,232
  • 5
  • 47
  • 69
Claudiu Haidu
  • 817
  • 4
  • 12
  • 24

2 Answers2

1

Your notice is coming from echo $_SESSION['cart_1']. And you are not using isset() there. Try it like:

if (isset($_SESSION['cart_1'])) {
    echo $_SESSION['cart_1'];
} else {
    echo "Session cart_1 is not set. Here is what is inside Session: " . implode(', ',array_keys($_SESSION));
}
nl-x
  • 11,762
  • 7
  • 33
  • 61
0
$_SESSION['cart_'.$_GET['add']] +'1';

This doesn't create a session-variable, if that's what you are expecting. You would set it with

$_SESSION['set_1'] = 0;

and increment it with

 $_SESSION['set_1']++;

I don't know what the 'add' variable might be. If it is, say, '2', then your session will be named set_21 not set_1, although the concatenation operator in php is '.' not '+'.

Andy G
  • 19,232
  • 5
  • 47
  • 69