title: How is a PDO result set stored
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>In the PHP Manual i learned to display the returned rows by <strong>iterating over the PDOStatement object</strong> 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 <strong>object's properties</strong>. The PDOStatement only has <strong>one property</strong> - $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?</p>
  
  <pre><code>// 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-&gt;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] &lt;br /&gt;";
  }
  
  // Outside the foreach loop, $result cannot be accessed this way.
  // This produces 'Cannot use object of type PDOStatement as array'
  echo $result[0]['Name'];
  </code></pre>