#47710 [Com]: Undefined Index when accessing results by array

From: Date: Thu, 30 Apr 2009 18:21:12 +0000
Subject: #47710 [Com]: Undefined Index when accessing results by array
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-136590@lists.php.net to get a copy of this message
 ID:               47710
 Comment by:       grant at coolhandjob dot com
 Reported By:      grant at coolhandjob dot com
 Status:           Feedback
 Bug Type:         PDO related
 Operating System: CentOS 5.2
 PHP Version:      5.3, 6CVS (2009-03-18)
 New Comment:

It returns:

Array ( [id] => 2 [0] => 2 [name] => cod [1] => cod ) Array ( [id] => 1
[0] => 1 [name] => mohaa [1] => mohaa ) 

I can access $row[0] etc just fine but not $row["id"] or $row["name"]
as thats when I get undefined index error.


Previous Comments:
------------------------------------------------------------------------

[2009-04-30 10:54:49] jani@php.net

What does this script output:

<?php
try {
  $pdo = new PDO("mysql:host=localhost;dbname=dbname;", "dbuser", 
"password");
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = 'SELECT id, name FROM games ORDER BY name';

  foreach ($pdo->query($sql) as $row) {
    print_r($row);
  }
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

------------------------------------------------------------------------

[2009-03-18 20:41:49] grant at coolhandjob dot com

Description:
------------
When trying to access the returned associative array I get a undefined
index error. Works as expected in PHP5.2.9 but have the same error with
the latest PHP5.3.

Reproduce code:
---------------
<?php
try {
	$pdo = new PDO("mysql:host=localhost;dbname=dbname;", "dbuser",
"password");
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

	$sql = 'SELECT id, name FROM games ORDER BY name';

    foreach ($pdo->query($sql) as $row) {
		print $row['id'] . " - ";
		print $row['name'] . "<br />";
	}
	print_r($row);
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

Expected result:
----------------
2 - cod
1 - mohaa
Array ( [id] => 1 [0] => 1 [name] => mohaa [1] => mohaa )

Actual result:
--------------
Notice: Undefined index: id in /var/www/html/temp.php on line 9
-
Notice: Undefined index: name in /var/www/html/temp.php on line 10


Notice: Undefined index: id in /var/www/html/temp.php on line 9
-
Notice: Undefined index: name in /var/www/html/temp.php on line 10

Array ( [id] => 1 [0] => 1 [name] => mohaa [1] => mohaa ) 


------------------------------------------------------------------------


-- 
Edit this bug report at http://bugs.php.net/?id=47710&edit=1



Thread (3 messages)

« previous php.bugs (#136590) next »