11

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();

14

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

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

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) {
  var_dump($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.

2
  • You have a typo. This should be foreach ($result as $record) { var_dump($record); }
    – vanz
    Jan 10 '13 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 '17 at 18:09
0

Try this

while($record = $result->fetchAssoc()) {
print_r($record);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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