为什么即使 var_dump() 显示索引已定义,我仍然收到未定义的索引错误?

Why do I keep getting an undefined index error even though var_dump() shows the index is defined?

提问人:taseaford 提问时间:12/20/2012 最后编辑:Jimtaseaford 更新时间:12/20/2012 访问量:726

问:

我正在创建一个应用程序来帮助跟踪我们青年事工的孩子们为夏令营赚取的奖学金。应用程序的这一部分从数据库中选择他们当前拥有的金额,将其保存到名为 $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 中的学生资金

31 号线在这里:

        $oldAmount = $studentFunds['studentFunds'];

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

数组 studentFunds 操作前的值:

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

此外,由于该错误,我的数据库没有使用新金额进行更新。

正如你所看到的,studentFunds指数确实包含一个值,那么为什么会这样。是我误解了错误,还是我的代码中有错误?

php 未定义索引

评论

5赞 PeeHaa 12/20/2012
它是一个多维数组。 应该得到你想要的$studentFunds[0]['studentFunds'];

答:

1赞 Ray 12/20/2012 #1

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

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

评论

0赞 taseaford 12/20/2012
伟大!感谢您@Ray和@PeeHaa的帮助!对于以后可能会偶然发现这个主题的任何人,这里有一个关于多demensional数组的教程。
2赞 Chris Ostmo 12/20/2012 #2

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

最精简的是,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'];
}

您要求出现丑陋的错误,或者更糟的是,如果您未能对查询结果进行至少基本的健全性检查,则会将意外记录打印到界面。