How do I check if the following code has results?

I tried the empty function but it always returns FALSE

$query = db_select('my_table', 't');
$query->condition('code', 10)
      ->fields('t', array('cid'));
$result = $query->execute();

3 Answers 3


If I'm correct the result of the execute() call should be a DatabaseStatementInterface which has a rowCount function.

  • 1
    Indeed, the following gives the number of results: var_dump($result->rowCount());
    – pfrenssen
    Oct 23, 2011 at 12:18

If you print var_dump($result); you will see that $result contains the query and other variables so it's never empty.
You can put $result in a foreach loop to see the results.

foreach ($result as $record) {

Inside the foreach loop, you can print the results with this code.

foreach ($result as $record) {
  print $record->nid;
  print $record->title;

If there is only one record as result use mysql_fetch_array() to handle the record.

  • You have a typo. This should be foreach ($result as $record) { var_dump($record); }
    – vanz
    Jan 10, 2013 at 13:47
  • With Drupal, it's a bad advice to suggest using a MySQL function. The site could be using PosgreSQL, SQLite, or another database engine with which Drupal is compatible. Drupal database functions don't require a module to know the database engine used from the side.
    – apaderno
    Nov 28, 2017 at 18:09

Try this

while($record = $result->fetchAssoc()) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.