【问题标题】:Warning adding value session array [duplicate]警告添加值会话数组[重复]
【发布时间】:2014-04-16 11:18:29
【问题描述】:

我正在开发一个购物车系统,当我第一次尝试添加产品时,它总是给我一个警告,内容如下:

注意:未定义索引:第 9 行 .../cart.php 中的 2

索引:2是id_product

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
        $product= $_POST['id_product'];
        $quantity= $_POST['qty'];
        $_SESSION['cart'][$product]+=$quantity;
    }

无论如何它都在添加值,但是在我刷新将出现在我的 foreach 表上的页面之后。我收到的值是正确的。

当我在另一个页面上登录后,我正在定义默认值。

$_SESSION['car'][0] = 0;

有什么建议吗?

【问题讨论】:

  • 感谢您的支持,但这对我没有帮助:/
  • @AndréFerreira 欢迎您。

标签: php arrays session cart


【解决方案1】:

在声明 $_SESSION['cart'][$product]+=$quantity; 中,您使用的是 +=,这就是导致问题的原因。

当您第一次添加产品时,它会抛出错误并且后记工作正常。

要解决这个问题,请执行以下操作。

$quantity= $_POST['qty'];
if(!empty($_SESSION['cart'][$product])){
     $quantity = $quantity + $_SESSION['cart'][$product];
}
$_SESSION['cart'][$product] = $quantity;

【讨论】:

  • 天啊!这不可能这么明显!非常感谢您的好意!
【解决方案2】:

您好,您需要将 id_product 设为有效变量,

$product=(isset($_SESSION['cart']) and $_SESSION['cart']!="") ? $_SESSION['cart'] : "";

if(isset($_POST['id_product'])){
    $product= $_POST['id_product'];
    $quantity= $_POST['qty'];

    if(!isset($_SESSION['cart'][$product])) {
        $_SESSION['cart'][$product] = $quantity;
    } 
    else { 
        $_SESSION['cart'][$product]+=$quantity;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 2023-04-05
    • 1970-01-01
    • 2021-05-17
    • 2014-10-29
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多