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'];
user1440560
source share