[support] db_select()->condition()

Michael Prasuhn mike at mikeyp.net
Sat May 26 03:47:17 UTC 2012


On May 25, 2012, at 2:16 PM, Earnie Boyd wrote:

> Uh, no it does not return the same thing or I would be able to do
> db_select()->execute()->fetch().
> 
> You must use foreach(db_select()->execute() as $row) to get the data
> and the data type of the first parameter of foreach is an array.

Nope, db_query() and SelectQuery::execute() *DO* return the same thing, and it's NOT an array. Just because you can use foreach does not make it an array. 

Both db_query() and SelectQuery::execute() return the exact same thing: an object of class DatabaseStatmentBase (may be different depending on the database being used) that implements DatabaseStatementInterface. These classes both implement the iterator interface which allows them to be, well, iterated upon as if they were arrays. 

If you read the code at http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7 and http://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3Aexecute/7 you can clearly see that they are both calling the same function as their return value.

Before you say that the code you suggested doesn't work please give it a try and actually run this:

<?php
$result = db_query("SELECT * FROM {node}");
print get_class($result) . "\n";

$result_2 = db_select('node', 'n')->fields('n')->execute();
print get_class($result_2);

Or this call to fetch() from the result of db_query() which you claim doesn't work:

<?php
$result = db_query("SELECT * FROM {node}");
var_dump($result->fetch());

$result_2 = db_select('node', 'n')->fields('n')->execute();
var_dump($result_2->fetch());

You'll notice that in the second example the results are identical.

You can read more about the Iterator interface at: http://www.php.net/manual/en/class.iterator.php.

-Mike

__________________
Michael Prasuhn
http://mikeyp.net




More information about the support mailing list