注意:即使使用ISSET,也会出现未定义的索引

时间:2014-05-16 21:40:23

标签: php indexing isset notice

我无法弄清楚为什么会收到错误。按下“添加”按钮后,通知会在刷新时消失。

<?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']
?>

--------和index.php

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

<?php products(); ?>

</body>
</html>

第一次执行index.php后,收到错误: 注意:未定义的索引:第35行的E:\ xamp \ htdocs \ ShopCart \ cart.php中的cart_1

2 个答案:

答案 0 :(得分:1)

您的通知来自echo $_SESSION['cart_1']。你没有在那里使用isset()。试试吧:

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));
}

答案 1 :(得分:0)

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

这不会创建会话变量,如果这是您所期望的。你可以用

设置它
$_SESSION['set_1'] = 0;

并用

递增
 $_SESSION['set_1']++;

我不知道'add'变量可能是什么。如果它是,例如'2',那么你的会话将被命名为set_21而不是set_1,尽管php中的连接运算符是'。'。不是'+'。

相关问题