【问题标题】:php session errorphp会话错误
【发布时间】:2010-12-11 21:57:03
【问题描述】:

我正在尝试制作购物车并从网上获取代码..

<?php
session_start();
require_once 'class/Item.php';
$product_id = $_REQUEST['i_id'];
$action = $_REQUEST['action']; 

$item= new Item();

if($product_id && !$item->productExists($product_id)) {
    die("Error. Product Doesn't Exist");
}

switch($action) { 
    case "add":
        $_SESSION['cart'][$product_id]++; 
    break;

    case "remove":
        $_SESSION['cart'][$product_id]--; 
        if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); 
    break;

    case "empty":
        unset($_SESSION['cart']); 
    break;
}
?>

但在将第一项添加到购物车时出错。我该如何纠正它。

错误:

注意:未定义索引:第 16 行 C:\wamp\www\website\store_esp\addtocart.php 中的购物车

注意:未定义索引:第 16 行 C:\wamp\www\website\store_esp\addtocart.php 中的 2

【问题讨论】:

  • 也许引用一个不存在的关联数组成员是错误的?
  • 可能是undefined index 警告。我在想$_SESSION['cart'][$product_id]++; 可能是问题所在。

标签: session session-variables session-state php


【解决方案1】:

看起来您可能正在尝试操作尚未设置的变量。确保在对 $_SESSION['cart'][$product_id] 进行操作之前检查它是否存在:

if(!isset($_SESSION['cart'][$product_id]))
  $_SESSION['cart'][$product_id] = 0;

switch($action) {
...

【讨论】:

  • 他还需要将if($_SESSION['cart'][$product_id] == 0) unset... 更改为if($_SESSION['cart'][$product_id] &lt;= 0) unset...
【解决方案2】:

尝试改变这个:

$_SESSION['cart'][$product_id]++;

到这里:

if (isset($_SESSION['cart'][$product_id])) {
    ++$_SESSION['cart'][$product_id];
} else {
    $_SESSION['cart'][$product_id] = 1;
}

【讨论】:

    【解决方案3】:

    如果不知道错误,就无法确定。但是使用我的演绎能力,我认为问题出在:

    $_SESSION['cart'][$product_id]++;
    

    应该是这样的:

    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id]++;
    } else {
        $_SESSION['cart'][$product_id] = 1;
    }
    

    你需要改变这个:

    session_start();
    // add this part
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
    }
    require_once 'class/Item.php';
    $product_id = $_REQUEST['i_id'];
    $action = $_REQUEST['action']; 
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2011-07-03
      • 2015-02-13
      相关资源
      最近更新 更多