Community Documentation

Count queries

Last updated November 23, 2012. Created by drupalshrek on November 23, 2012.
Log in to edit this page.

Count queries

Any query may have a corresponding "count query". The count query returns the number of rows in the original query. To obtain a count query, use the countQuery() method.

<?php
$count_query
= $query->countQuery();
?>

$count_query is now a new Dynamic Select query with no ordering restrictions that when executed will return a result set with only one value, the number of records that would be matched by the original query. Because PHP supports chaining methods on returned objects, the following idiom is a common approach:

<?php
$num_rows
= $query->countQuery()->execute()->fetchField();
?>

About this page

Drupal version
Drupal 7.x
Audience
Programmers
Level
Intermediate, Advanced
Drupal’s online documentation is © 2000-2013 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. Comments on documentation pages are used to improve content and then deleted.