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

时间:2013-01-03 18:08:04

标签: php mysql session shopping-cart

我目前正在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'];

?>

1 个答案:

答案 0 :(得分:0)

您应该在使用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_reporting ini php.ini可能设置为E_ALL & ~E_NOTICE

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

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