How is the PDO result set stored?

I have been learning PHP for 2 months as my first scripting language. For most of my problems, I can easily find the answer on the Internet, but there is something about PDO that I do not seem to understand.

To get data from the database, I create a new object of the PDO class and call the PDO :: query () method. This returns a PDOStatement object that carries the result set from the SQL query. Here is where the problem begins. I cannot understand how and where the data from the result set is stored.

In the PHP manual, I learned how to display returned strings by iterating over a PDOStatement object using 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 properties of the object . PDOStatement has only one property - $ queryString - containing a string of issued queries. So ... where are the query results stored? And why can I contact them through an array with a foreach loop, but not beyond?

// 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']; 
+7
source share
1 answer

The PDOStatement class implements the Iterator interface, which allows you to run its objects through.

 Iterator extends Traversable { /* Methods */ abstract public mixed current ( void ) abstract public scalar key ( void ) abstract public void next ( void ) abstract public void rewind ( void ) abstract public boolean valid ( void ) } 

For an object that implements the Iterator interface,

 foreach($result as $row) { // Code } 

equivalently

 for ($result->rewind(); $result->valid(); $result->next()) { $row = $result->current(); // Code } 
+6
source

All Articles