在简单的添加功能中使用会话


Using sessions in simple add function

我目前正在youtube上的PHP学院学习PHP教程,我们正在创建一个购物车。到目前为止,我们使用会话来说明添加的产品。当我尝试回显会话时,它会产生Notice: Undefined index: cart_1 in C:'Program Files'wamp'www'Formula One'script'cart.php on line 28错误。为什么会这样呢?在教程视频中,它在下一页添加了一个1,当再次点击时,它会变为2。在他们的论坛上有一些建议以前使用ISSET。谢谢你很多。

 <?php
session_start();
include("../script/dbconnect.php");
$page1 = 'index.php'; //page reference
if (isset($_GET['add'])) { // cart add button
    $_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!";
    }
else {
  while ($get_row = mysql_fetch_assoc($get)) {
        echo '<p>'.$get_row['name'].'<br />'.$get_row['description'].'<br />'.$get_row['price'].' <a href="cart.php?add='.$get_row['id'].'">Add Here</a></p>';
        }
    }
}
echo $_SESSION['cart_1'];
?>

你应该在使用可能未定义的变量之前添加一个检查

if(!isset($_SESSION['cart_'.$_GET['add']])) 
       $_SESSION['cart_'.$_GET['add']] = 0;
$_SESSION['cart_'.$_GET['add']]+='1';

if(isset($_SESSION['cart_1']))
    echo $_SESSION['cart_1'];
else
    echo "session cart_1 not defined";

在链接视频中没有显示错误,因为作者的error_reporting ini php.ini可能设置为E_ALL & ~E_NOTICE

编辑:我现在看到视频了。请尝试找到另一个教程在:
  • error_reporting设置为E_ALL
  • 使用pdo_*函数代替mysql_*