I’m wondering about why you can set the fetch mode before and after the query is executed, and the result still uses the given fetch mode…?
That means that PDO retrieve the query result both as numeric and assoc from the db server? Hmm…
Is it possible only to retrieve one..? Either the numeric result or the assoc result?
These two examples return the exact same results.. If I leave setFetchMode out both the numeric and the assoc result is printed
Before execute
$sth = $dbh->prepare("SELECT REFERENCED_TABLE_NAME table_name, REFERENCED_COLUMN_NAME column_name\n"
."FROM KEY_COLUMN_USAGE\n"
."WHERE REFERENCED_TABLE_NAME IS NOT NULL && REFERENCED_COLUMN_NAME IS NOT NULL\n"
."GROUP BY REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
echo '<pre>';
foreach($sth as $row){
print_r($row);
}
echo '</pre>';
After execute
$sth = $dbh->prepare("SELECT REFERENCED_TABLE_NAME table_name, REFERENCED_COLUMN_NAME column_name\n"
."FROM KEY_COLUMN_USAGE\n"
."WHERE REFERENCED_TABLE_NAME IS NOT NULL && REFERENCED_COLUMN_NAME IS NOT NULL\n"
."GROUP BY REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME");
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
echo '<pre>';
foreach($sth as $row){
print_r($row);
}
echo '</pre>';
Your example uses a simplification: after execution, but before you can use the records, you also need to fetch them. These are the fetch and fetchAll methods in the PDOStatement class.
But when using the foreach construct, you are using PDOStatement’s Traversable interface, which calls the fetchAll method instead of you, at the start of the foreach loop.
So in both examples, fetchAll gets called after you set the fetch mode.
Edit:
PDO won’t fetch the records from the DB in one or two way, it will always do it in the same way – the difference is just how it will present the results to you. If you specify a fetch mode, PDO will build the requested structure for you. If you use the default, or specify FETCH_BOTH, it will build you two different representation, but from the same result set. This parameter won’t make in difference in the commands sent to the SQL server.