I’ve been studying PHP for 2 months now as my first scripting language. For most of my problems i can easily find an answer online, but there’s something about PDO that i can’t seem to understand.
In order to retrieve data from a database I instantiate a new object of the PDO class and call the PDO::query() method on it. This returns a PDOStatement object which carries the result set from the SQL query. Here’s where the problem starts. I can’t seem to understand how and where the data from the result set is stored.
In the PHP Manual i learned to display the returned rows by iterating over the PDOStatement object with a foreach loop. However, the PHP manual clearly states that if an object is converted to an array, the result is an array whose elements are the object’s properties. The PDOStatement only has one property – $queryString – containing the issued query string. So… where are the query results stored? And why can I reach them through an array with a foreach loop, but not outside of it?
// Instantiate new PDO object to establish a new connection with MySQL database
$db = new PDO('mysql:dbhost=localhost;dbname=world', 'root', 'secret');
// Execute SQL query - Returns a PDOStatement object
$result = $db->query("SELECT Name, Continent, Population FROM Country");
// Result set can be accessed with a foreach loop iterating over the PDOStatement object
foreach ($result as $row) {
echo "$row[Name] - $row[Continent] - $row[Population] <br />";
}
// Outside the foreach loop, $result cannot be accessed this way.
// This produces 'Cannot use object of type PDOStatement as array'
echo $result[0]['Name'];
The PDOStatement class implements the Iterator interface, which lets its objects be iterated through.
For an object that implements the Iterator interface,
is equivalent to