【问题标题】:Using sessions in simple add function在简单的添加功能中使用会话
【发布时间】:2013-01-03 18:08:04
【问题描述】:

我目前正在 YouTube here 上关注 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'];

?>

【问题讨论】:

  • 通知告诉你 $_SESSION['cart_1'] 没有定义。您可以在使用前检查它,或者您可以在 php.ini 中禁用此消息,因为这不是严重错误
  • 如果有教程提到mysql_query扔掉。此接口来自 1990 年代,已弃用,注定要被删除,并且会在 PHP 5.5 或更高版本中产生警告。新应用程序应使用PDO 以避免严重的 SQL 注入错误。

标签: php mysql session shopping-cart


【解决方案1】:

您应该在使用可能未定义的 var 之前添加检查

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_reportingini php.ini 可能设置为E_ALL &amp; ~E_NOTICE

编辑:我现在看到了视频。请尝试在以下位置找到另一个教程:

  • error_reporting 设置为E_ALL
  • 使用pdo_*函数代替mysql_*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2017-02-03
    • 2014-05-20
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多