How to do mysql_num_rows() in Drupal 7

Posted on January 16, 2012


Drupal 7 uses it’s own database API, so using simple PHP functions like mysql_num_rows() does not work. Drupal API isn’t very up to date with this, but the earlier db_num_rows() function does not exist anymore, and db_affected_rows() is not good either, because you can’t use it with SELECT queries.

Answer is to use method called rowCount(). As Drupal 7 is turning all database results into objects, there is no function to find out the amount of results. Also it is not possible to go through the results just to count them, as the result object will empty itself after first iteration.

To use rowCount(), do the query and call the method like this:


Enclosed screenshot has an if statement with rowCount(), shot from Vim text editor. Method rowCount() in Drupal 7 API.