【问题标题】:Why do I keep getting an undefined index error even though var_dump() shows the index is defined?为什么即使 var_dump() 显示索引已定义,我仍会收到未定义的索引错误?
【发布时间】:2012-12-07 06:02:02
【问题描述】:

我正在创建一个应用程序来帮助跟踪我们青年部的孩子们在夏令营中获得的奖学金。应用程序的这一部分从数据库中选择他们当前拥有的金额,将其保存到名为 $oldAmount 的变量中,将其添加到 $fundsAmount,并使用新的资金金额更新数据库。

    //Select student's current allocated funds amount and save to $studentFunds array
    $selectQuery = "SELECT studentFunds FROM students WHERE studentNum = $studentNum";
    $selectStatement = $db -> prepare($selectQuery);
    $selectStatement -> execute();
    $studentFunds = $selectStatement -> fetchAll();

    //DEBUG: Display value of studentFunds array
    echo "Value of array studentFunds before operation: ";
    var_dump($studentFunds);

    //Save the value of $studentFunds['studentFunds'] to $oldAmount
    $oldAmount = $studentFunds['studentFunds'];

    //Perform operation: add old amount and new funds amount together
    $studentNewAmount = $oldAmount + $fundsAmount; 

    //DEBUG: display $studentNewAmount
    echo "Value of studentNewAmount after operation: ";
    echo $studentNewAmount;

    //DEBUG: $studentNewAmount = 255;
    $db -> query("UPDATE students SET studentFunds = '$studentNewAmount' WHERE studentNum = $studentNum");

由于某种原因,我每次运行应用程序时都会收到此错误:

注意:未定义索引:第 31 行 C:\xampp\htdocs\scholarshipManager\model\insertAllocation.php 中的 studentFunds

第 31 行在这里:

        $oldAmount = $studentFunds['studentFunds'];

var_dump() 显示 $studentFunds 数组的以下内容:

数组studentFunds运算前的值:

array(1) { 
    [0]=> array(2) { 
            ["studentFunds"]=> string(3) "200"
            [0]=> string(3) "200" 
    }
} 

另外,由于该错误,我的数据库没有更新为新的数量。

如您所见,studentFunds 索引确实包含一个值,那么为什么会发生这种情况。是我误解了错误还是我的代码有错误?

【问题讨论】:

  • 它是一个多维数组。 $studentFunds[0]['studentFunds']; 应该能得到你想要的

标签: php undefined-index


【解决方案1】:

奥马尔的回答是正确的。有关更多详细信息,请查看 fetchAll 的文档: PHP docs for fetchAll

简单的是 fetchAll 从您的查询中返回一个包含所有行的索引数组,并且每个索引数组都包含一个键和值的关联数组。结果你要的数据就存放在$studentFunds[0]['studentFunds']

由于 fetchAll 返回一个数组,如果您使用 print_r 而不是 var_dump,对此类问题的故障排除应该会更快。 print_r 的输出格式更适合于挑选(理解)数组。

作为一种实践,您还应该将其包装到某种形式的健全性检查中,以防例如传入的 $studentNum 无效或在数据库中找不到或找到多条记录。像这样的:

$oldAmount = 0;
if( is_array( $studentFunds ) && count( $studentFunds ) == 1 )
{
   $oldAmount = $studentFunds[0]['studentFunds'];
}

如果您没有对查询结果进行至少基本的完整性检查,您要求的是丑陋的错误,或者更糟的是,将意外记录的结果打印到界面上。

【讨论】:

    【解决方案2】:

    $studentFunds 是一个包含一个元素的数组。在第 31 行试试这个:

     $oldAmount = $studentFunds[0]['studentFunds'];
    

    【讨论】:

    • 太棒了!感谢@Ray 和@PeeHaa 的帮助!对于以后可能会偶然发现此主题的任何人,这是Multidemensional arrays. 上的教程
    猜你喜欢
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多