Query count()
Any query can have a corresponding "count query". A count query returns the number of rows in the original query. To get a count query from an existing query (which is a select query object implementing the SelectInterface), use the countQuery()
method.
$count_query = $query->countQuery();
$count_query
is now a new dynamic select query without order constraints, which when executed will return a result set with only one value — the number of records that would match the original query. Since PHP supports method chaining on returned objects, the following approach is common:
$num_rows = $query->countQuery()->execute()->fetchField();
For an entity query (implementing the QueryInterface), the code is slightly different:
$num_rows = $query->count()->execute();
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.