How do I paginate results with db_query in Drupal 7? I didn't find any example using db_query.


db_select() is the way to go using a so called query extender. Here is a simple example:

$query = db_select('node', 'n')
  ->condition('type', 'article')

Then theme_pager() can be used for outputting a pager.

Find more details on this drupal.org working example


The following code works successfully for me.

$limit = 10;
$start = isset($_REQUEST['page']) ? $_REQUEST['page'] * $limit : 0;
$query = "<your query>";
$count_query = "<count query>";//count(*) AS total
$count_result = db_query($count_query);
$query_items = db_query_range($query,$start,$limit);
$items = $query_items->fetchAll();

pager_default_initialize($count_result->total, $limit, $element = 0);
$pager = theme('pager',array("quantity"=>5));
return theme("<page-theme>",array("items"=>$items ,"pager"=>$pager));

This worked for me:

  // $list is the list of items you are paging through
  $list = array('Cat', 'Dog', 'Mouse', 'Horse', 'Pony', 'Winged mongoose');
  $per_page = 2;

  // Initialise the pager
  $current_page = pager_default_initialize(count($list), $per_page);

  // Split your list into page sized chunks
  $chunks = array_chunk($list, $per_page, TRUE);

  // Show the pager
  print theme('pager', array('quantity', count($list)));

  // Show the appropriate items from the list
  print theme('item_list', array(
      'items' => $chunks[$current_page],

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.