Why do I get 'Undefined offset: 0'?

这一生的挚爱 提交于 2019-12-25 04:05:26

问题


I'm develop a website and it looks fine. Then I turned on debugging to see if I had any errors, and I get this message:

Notice: Undefined offset: 0 in I:\path\to\file\MyFile.class.php on line 105

On that line you will find the following code:

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result[0]; // line 105

If I do a print_r(result) I get the following result:

Array (
    [0] => Array (
        [id] => 3721
        [parentID] =>
    )
)
Array (
) 

As you can see the result contains twoarrays. The first one has data, the second one has no data. I've never seen print_r output two arrays like this. I'm guessing it's the second one causing me the problems.

Can anyone advice me of why that second array sneaks in?

VAR dump

array
  0 => 
    array
      'id' => string '3721' (length=4)
      'parentID' => null
array
  empty

回答1:


You fetch all records matching the query. If there are no records it will return an empty array. Obviously there is no 0 element in an empty array.



来源:https://stackoverflow.com/questions/7460639/why-do-i-get-undefined-offset-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!