Drupal 6 num_rows

I’ve been working on a site powered by Drupal and needed to find the number of rows a database query returned. Simple enough and quite common procedure. But, the Drupal database API no longer offers the db_num_rows() function.

I had a quick Google around and the answered seemed to be to run the query twice but the second time using a count query. Two calls to the database when only one is necessary? Not on my watch. The piece of code is to appear on the home page so it will be called upon frequently.

My solution was too loop through the results set and add the formatted HTML to an array. Then check if there are any items in the array, if so loop through it an output them if not display the message that there are currently no results.

I know it’s still doubling up but I think it is a slightly more elegant solution than the double database call.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

3 Responses to Drupal 6 num_rows

  1. ian says:

    Thanks Edwas,

    Here is some sample code which shows how I did it.

    <?php

    // Get all events that are still to happen
    $events_result = db_query("SELECT * FROM `node` `node`.`type` = 'forthcoming_events' AND `field_event_date_value` > NOW( ) ORDER BY `field_event_date_value` DESC LIMIT 5");

    // Create an array to hold the events
    $events_array = array();

    // Loop through the results and add them to the array
    while($events = db_fetch_array($events_result)) {

    $events_array[] = '<dd>'.$events['title'].'<br /><a href="index.php?q=node/'.$events['nid'].'">Find out more ></a></dd>';

    }

    // Check if any events were added to the array
    if(count($events_array) != 0) {

    // If there were any events display them
    echo "<dl>";

    foreach($events_array as $key => $value) {
    echo $value;
    }

    echo "</dl>";

    } else {

    // There were no events so display a link to see old events
    echo '<p><a href="/index.php?q=node/35">View recent events</a></p>';

    }

    ?>

  2. Vensires says:

    This is a very old post but anyways. You can always use
    $result = db_query($sql_string_here);
    and then do a
    if($result->num_rows > 0){
    //do whatever you want here
    }

    🙂

  3. Lucky says:

    You can use:
    $result = db_query($SQL, array(\’:some_id\’=>$some_id);
    and then
    $count = $result->fetchField()

    $count will contain the number of records fetched.

Leave a Reply

Your email address will not be published. Required fields are marked *