2

In my custom module for Drupal 8, I am using the following code.

$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();

I can get the number of rows looping over $result.

foreach ($result as $row) {
  $num++;
}

Is there a way to get the number of rows with a function / class method?

4
$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();
$records = $result->fetchAll();
$num_results = count($records);

This will leave you with $records being an array of all records and $num_results being the count of that array.

See: https://www.drupal.org/docs/8/api/database-api/result-sets

Also: Select documentation and StatementInterface (the return val of $query->execute) documentation

You may want to look into using entity queries, though I'm not sure what your goal is.

  • no that always gives me a 1 but that is not the number of results . that doesn't work in drupal 8 queries – Diana Apr 18 '18 at 17:37
  • I updated - this should work. – sonfd Apr 18 '18 at 17:55
  • This works on Drupal 7? – DarckBlezzer Oct 20 '18 at 18:53
3

Use $query->countQuery()->execute()->fetchField(); This is fast.

See detail example.

$number = $this->connection->select(static::TABLE_NAME, 'f')
    ->condition('event', $name)
    ->condition('identifier', $identifier)
    ->condition('timestamp', REQUEST_TIME - $window, '>')
    ->countQuery()
    ->execute()
    ->fetchField();

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.