example of using pager_query()

nadongtae - May 8, 2007 - 02:32

Can anyone show me an example how to use pager_query() which is more detail than the example in http://api.drupal.org/api/HEAD/function/pager_query.

Here you go...

NancyDru - May 8, 2007 - 02:58

Useful code that can be stolen from the taxonomy module:

function taxonomy_select_nodes($tids = array(), $operator = 'or', $depth = 0, $pager = TRUE, $order = 'n.sticky DESC, n.created DESC') {
  if (count($tids) > 0) {
    // For each term ID, generate an array of descendant term IDs to the right depth.
    $descendant_tids = array();
    if ($depth === 'all') {
      $depth = NULL;
    }
    foreach ($tids as $index => $tid) {
      $term = taxonomy_get_term($tid);
      $tree = taxonomy_get_tree($term->vid, $tid, -1, $depth);
      $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));
    }

    if ($operator == 'or') {
      $str_tids = implode(',', call_user_func_array('array_merge', $descendant_tids));
      $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid IN ('. $str_tids .') AND n.status = 1 ORDER BY '. $order;
      $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid IN ('. $str_tids .') AND n.status = 1';
    }
    else {
      $joins = '';
      $wheres = '';
      foreach ($descendant_tids as $index => $tids) {
        $joins .= ' INNER JOIN {term_node} tn'. $index .' ON n.nid = tn'. $index .'.nid';
        $wheres .= ' AND tn'. $index .'.tid IN ('. implode(',', $tids) .')';
      }
      $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres .' ORDER BY '. $order;
      $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres;
    }
    $sql = db_rewrite_sql($sql);
    $sql_count = db_rewrite_sql($sql_count);
    if ($pager) {
      $result = pager_query($sql, variable_get('default_nodes_main', 10), 0, $sql_count);
    }
    else {
      $result = db_query_range($sql, 0, variable_get('feed_default_items', 10));
    }
  }

  return $result;
}

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

It's too complicated

nadongtae - May 8, 2007 - 09:19

The code is so complicated. Can you give me a simple one ? It will be better if you can show me a simple module . Thanks for your supporting

Try this one

NancyDru - May 8, 2007 - 13:42

  $items_per_page = variable_get('default_nodes_main', 10);
  $select = "SELECT n.title, n.nid, n.uid, n.created FROM {node} n ";
  $where = "WHERE n.type='pinkslip' AND n.status = 1 ";
  $order = "ORDER BY n.sticky DESC, n.created DESC";

  $sql_count = db_rewrite_sql('SELECT COUNT(DISTINCT(nid)) FROM {node} WHERE status = 1 AND type = "pinkslip"');

  $result = pager_query($select . $where . $order, $items_per_page, 0, $sql_count);

  $output .= pinkslip_render_nodes($result);

  $output .= theme('pager', NULL, $items_per_page, 0);

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

pager_query is not working for me

sujith7c - July 8, 2008 - 06:50

friend

here i have some problem with pager_query

$sqlquery="SELECT profile.nid,profile.field_name_value,profile.field_age_value,profile.field_sex_value,profile.field_height_value,t1.name AS caste,t2.name AS religion,t3.name AS location,files.filepath AS imgloc FROM {content_type_profile} AS profile INNER JOIN term_data AS t1 ON profile.field_caste_tid=t1.tid INNER JOIN term_data AS t2 ON profile.field_religion_tid=t2.tid INNER JOIN term_data AS t3 ON profile.field_location_tid=t3.tid LEFT JOIN files ON (files.nid=profile.nid-1 AND files.filename='".$Imagetpe."') WHERE profile.field_sex_value='".$sex."'";

$Countqry="SELECT COUNT(*) FROM {content_type_profile} AS profile INNER JOIN term_data AS t1 ON profile.field_caste_tid=t1.tid INNER JOIN term_data AS t2 ON profile.field_religion_tid=t2.tid INNER JOIN term_data AS t3 ON profile.field_location_tid=t3.tid LEFT JOIN files ON (files.nid=profile.nid-1 AND files.filename='".$Imagetpe."') WHERE profile.field_sex_value='".$sex."'";

$sqlquery=$sqlquery." AND profile.field_age_value BETWEEN'".$age_lower_limit."' AND '".$age_upper_limit."' ORDER BY profile.nid DESC";

$GL_count_query=$Countqry." AND profile.field_age_value BETWEEN'".$age_lower_limit."' AND '".$age_upper_limit."'";

$result=pager_query($sqlquery,10,0,$GL_count_query);

while($data= db_fetch_object($result))
{
//,...............some code here
}

$search_result = theme('table',$header,$newdata);
$srch_rslt .=$search_result;
$srch_rslt .=theme('pager');

it is showing ten records but there is no links other result page

Hmm...

NancyDru - July 8, 2008 - 15:08

If you only have ten records there won't be any pager links.

NancyDru (formerly Nancy W. until I got married to Drupal)

pager_query is not working for me

sujith7c - July 9, 2008 - 07:13

There are more than 10 records

it is showing only ten records
there is no link to other result page

Count SQL?

dwees - July 9, 2008 - 13:20

Have you confirmed that the count(*) sql you are using actually produces the right number of records? If your count query is incorrect, this could be the problem.

Dave

My site: http://www.unitorganizer.com/myblog

I'm Probably Missing Something Obvious

Mark in SC_USA - August 27, 2009 - 20:28

I've adapted examples from the Drupal site to come up with the below code. I get the pager display with the correct number of pages based on the number of records meeting the SELECT criteria, but instead of data returned from the database, I get:

"Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74Resource id #74".

What do I need to do to get the actual data to display? Any help greatly appreciated.

function pager_test(){

drupal_set_title("Pager Test");

//This is numbers per page
$num_per_page = 12;

//actual query
$query = "SELECT STORE_ID AS ID, STORE_STATE AS STATE FROM {stores} WHERE STORE_STATE = 'SC'";

//the count query should be similar to the query above
$count_query = "SELECT COUNT(*) AS row_count FROM {stores} WHERE STORE_STATE = 'SC'";

//pager_query function
$rs = pager_query($query, $num_per_page, 0, $count_query);

while ($data = db_fetch_object($rs)){
$output .= $rs;
}

//dont forget
$output .= theme('pager');

return $output;
}

Try this

NancyDru - August 28, 2009 - 05:18

function pager_test(){
  drupal_set_title("Pager Test");

  //This is numbers per page
  $num_per_page = 12;

  //actual query
  $query = "SELECT STORE_ID AS ID, STORE_STATE AS STATE FROM {stores} WHERE STORE_STATE = 'SC'";

  //pager_query function
  $rs = pager_query($query, $num_per_page);

  while ($data = db_fetch_object($rs)){
    $output .= $rs;
  }

  $output .= theme('pager', array(), $num_per_page);
  return $output;
}

It's a simple query; you don't need a count query. But it might help to tell the pager theme how many per page.

BTW, you might also be interested in http://drupal.org/coding-standards

Thanks for Reply

Mark in SC_USA - August 28, 2009 - 12:02

Hey Nancy, thanks for a quick reply.

Using the example you posted, I get the same "Resource ID #74 displayed 12 times. However, the code is cleaner and more to the point, so I'll keep trying with it. I'll also take a lookie at the coding standards link.

Oops

NancyDru - August 28, 2009 - 14:18

Yes, I guess you would.

function pager_test(){
  drupal_set_title("Pager Test");

  //This is numbers per page
  $num_per_page = 12;
  $items = array();

  //actual query
  $query = "SELECT STORE_ID AS id, STORE_STATE AS state FROM {stores} WHERE STORE_STATE = 'SC'";

  //pager_query function
  $rs = pager_query($query, $num_per_page);

  while ($data = db_fetch_object($rs)) {
    $items[] = $data->id;
  }

  return theme('item_list', $items) . theme('pager', array(), $num_per_page);
}

Doh!

Mark in SC_USA - August 28, 2009 - 14:59

It's the simplest things that usually trip me up.

Went back and looked at a project I had done in MySQL/PHP where I displayed paged results. Below is the code that now works. Thank you for the nudge in the right direction.

While I'm thinking about it, on the line "$nd .= ( - );", my intention was to put some space between the 2 columns. Is there a better way to do this? A reference to a good example of how to include header info in the query results would probably be spot on.

function pf_test(){

drupal_set_title("Pager Test");

  //This is numbers per page
  $num_per_page = 12;

  $output = '';

  //actual query
  $query = "SELECT store_id as ID, store_name as Name FROM {stores} WHERE store_state = 'sc'";

  //pager_query function
  $rs = pager_query($query, $num_per_page);

  while ($data = db_fetch_object($rs)){
    $nd = ($data->ID);
    $nd .= (' -  ');
    $nd .= ($data->Name);
    $nd .= ('<br /> <br />');
    $output .= ($nd);
  }

  $output .= theme('pager', array(), $num_per_page);
  return $output;
}

Here you go

NancyDru - August 28, 2009 - 15:47

This will give you a table that you can add attributes to if you want. It automatically allows you to colorize the odd and even rows. HowTo: Create Simple Tables

function pf_test() {
  drupal_set_title("Pager Test");
  //This is numbers per page
  $num_per_page = 12;
  $header = array('ID', 'Name');
  $rows = array();

  //actual query
  $query = "SELECT store_id as ID, store_name as Name FROM {stores} WHERE store_state = 'sc'";

  //pager_query function
  $rs = pager_query($query, $num_per_page);

  while ($data = db_fetch_object($rs)){
    $rows[] = array($data->ID, $data->Name);
  }
 
  return theme('table', $header, $rows) . theme('pager', array(), $num_per_page);
}

http://api.drupal.org/api/function/theme_table/6

Awesome!

Mark in SC_USA - August 28, 2009 - 17:49

That is so cool. Thank you very much for taking the time to help a "Drubie" (you probably figured it out, but it's Drupal Newbie).

We all were

NancyDru - August 29, 2009 - 01:58

We all were newbies at one time. When you find one who is trying, it is a pleasure to help.

i was in the same boat as

gains - May 8, 2007 - 13:42

i was in the same boat as you a couple of weeks ago..it worked for me

<?php
//This is numbers per page
$num_per_page = 10;

//actual query
$query = "SELECT nid,uid FROM {node} WHERE uid=%d AND type='jobs' ORDER BY created DESC";

//the count query should be similar to the query above
$count_query = "SELECT COUNT(*) AS row_count FROM {node} WHERE uid=%d AND type='jobs' ORDER BY created DESC";

//pager_query function
$result = pager_query($query, $num_per_page, 0, $count_query, $user_load->uid);

//dont forget
$output .= theme('pager');
?>

Hope this helps..

--------------------------------------------------
http://www.usingdrupal.com
Tutorial Screencasts

Thanks for your supporting but

nadongtae - May 9, 2007 - 01:12

Because i'm so new to drupal, Can you show me how it works in a simple module ? I mean if you can show me a demo for that . Thanks you very much .

Can you send a simple source code

nadongtae - May 9, 2007 - 01:47

This is my email address : kanguru1225@gmail.com. Can you send me a simple demo ?

Complicated but well commented demo

dwees - October 10, 2007 - 02:38

If you download the new project, og_management, and read the source code for this module, in the 'og_management_load_subscribers' function, I use pagination when I do a couple of the queries.

Dave

My site: http://www.unitorganizer.com/myblog

How to apply pagintation to a table (array)

raffuk - October 9, 2007 - 14:29

Hi I'm new in drupal and I'm trying to do a pagination in a table which the results are coming from an array.

The array looks like this :

Array
(
    [0] => Array
        (
            [0] =>Product 1   
            [1] => $1.05
        )

    [1] => Array
        (
            [0] => Product 2  
            [1] => $1.85
        )
and so on (more then 100 results...
)

I have no idea how to do that, please help?

Thanx

-Raff

Pagination is for Database queries

dwees - October 10, 2007 - 02:36

Drupal Pagination is for database queries, if you are constructing your array in a different way, you'll have to custom create the pagination as far as I know.

However, presumably at some stage you are collecting information from the database, although it could be well before that array is constructed.

How do you know how many rows there will be in your table anyway?

Dave

My site: http://www.unitorganizer.com/myblog

Well...

NancyDru - October 10, 2007 - 04:29

I think he wants more than this

dwees - October 10, 2007 - 07:20

I think he wants to take his giant array and display parts of it depending on which link the user chooses. Ie, generate a huge array, and display parts of it. However since most building of arrays can be eventually traced back to some database query, I'm pretty sure he can find a way to use pager_query.

Dave

My site: http://www.unitorganizer.com/myblog

A similar kind of query based on the pagination

preselkarthik - May 6, 2008 - 04:37

Hi,
I am new to Drupal. I tried using pager_query() for my data to be shown as a paginated result. I have a problem here. My table consists of some 30000 rows and i want to show only the 1st 50 records which are descending ordered. Looking at the code for the pager_query, it is constructed in a way that i could not limit the records retrieved as per my wish. Irrespective of whatever is the number of records i need to show in my site, drupal wants to retrieve all the records from the table. Hope my question is clear. To put in simple words, "How can i show only a limited number of rows that i desire instead of retrieving all the records from the table?"

Any help is greatly thanked.

Regards,
~ Presel Karthik

LIMIT

NancyDru - May 6, 2008 - 04:44

Have you tried using the LIMIT clause? SELECT * FROM ... ORDER BY ... LIMIT 50

Nancy Dru (formerly Nancy W. until I got married to Drupal)

Yes. I tried using the limit

preselkarthik - May 6, 2008 - 04:47

Yes. I tried using the limit clause. But the results were not shown when i used the limit. I am looking more deep into it now.

Well as per my

preselkarthik - May 6, 2008 - 04:55

Well as per my understanding, i have to pass 'the actual query' as well as 'the query to get the count of records' as parameters to the pager_query function right?

Based on this understanding i passed 'the actual query' and the 'same query with limits' - to get the count, but then i get the result as follows:

The first scenario is i need 50 records and those records will be displayed in pages of 10 records each. So total 5 pages. Now the page 1-4 shows 10 records each and the 'Showing 10 of 50' was same as i pasted here. But for the 5th page, the number of records shown is 10, which is as expected, but 'Showing 0 of 50' is displayed in the top left part of the pagination which NOT correct.

The second scenario is i gave 0,49 in the limit of the 'the query to get the count of records'. But the result is again total 5 pages.And the page 1-4 shows 10 records each and the 'Showing 10 of 50' was same as i pasted here. But for the 5th page, the number of records shown is 10, which is NOT as expected, but 'Showing 9 of 49' is displayed in the top left part of the pagination as expected.

It depends

NancyDru - May 6, 2008 - 12:56

The count query is only needed if the query is complex.

Nancy Dru (formerly Nancy W. until I got married to Drupal)

Also i tried giving limit in

preselkarthik - May 6, 2008 - 04:56

Also i tried giving limit in the actual query also. This does not give me any result but blank

I think i found a patch for

preselkarthik - May 6, 2008 - 05:50

I think i found a patch for this...

http://drupal.org/node/65169

Need to try implementing this

It does not solve my problem

preselkarthik - May 6, 2008 - 06:02

It does not solve my problem of getting 'Showing 0 of 50' in the last page even though i get last 10 records out of the total 50 records my query retrieved.

Any help greatly appreciated.

I never knew this existed

stripped your speech - July 9, 2008 - 14:13

I never knew this existed before today. Here is what I am doing:

function beracah_page_homes($query) {

$count = db_result(db_query($query));
$query_count = db_query("SELECT $count");
$result = pager_query("$query, 10, 0, $count_query");

// do your code here... put code in $output

// display navigation
$output .= theme('pager', NULL, 10);
return $output;

}

The pagination outputs at the bottom fine. But when I hit a page number or Next, I just get a blank page. Anyone know why? I am passing a predefined $query into this function, it is coming from a form POST / real estate search form.

I feel like im very close.

==============
delaware web design
delaware website design

???

NancyDru - July 10, 2008 - 01:43

I don't see how this could work, but I am far from a MySql expert.

It works perfectly- I can

stripped your speech - July 10, 2008 - 02:34

It works perfectly- I can post the code I came up with when I get back to work tomorrow.

==============
delaware web design
delaware website design

Here we are. This is what I

stripped your speech - July 10, 2008 - 13:30

Here we are. This is what I came up with that works. This is for a page with a listing of homes for sale, similar to the way this page looks http://www.houseplans.com/asearch.asp:

function theme_paged_homes() {
        if($_GET["homeType"]) {
$homeType = $_GET["homeType"];
} else {
$homeType = $_POST["homeType"];
}

if($_GET["homeName"]) {
$homeName = $_GET["homeName"];
} else {
$homeName = $_POST["homeName"];
}

if($_GET["bedrooms"]) {
$bedrooms = $_GET["bedrooms"];
} else {
$bedrooms = $_POST["bedrooms"];
}

if($_GET["bathrooms"]) {
$bathrooms = $_GET["bathrooms"];
} else {
$bathrooms = $_POST["bathrooms"];
}

if($_GET["sqFootMin"]) {
$sqFootMin = $_GET["sqFootMin"];
} else {
$sqFootMin = $_POST["sqFootMin"];
}

if($_GET["sqFootMax"]) {
$sqFootMax = $_GET["sqFootMax"];
} else {
$sqFootMax = $_POST["sqFootMax"];
}

$query = "your query here";

if ($homeType != '') {
$query .= ' AND cth.field_type_value = "'.$homeType.'"';
}

if ($homeName != '') {
$query .= ' AND n.title = "'.$homeName.'"';
}

if ($bedrooms != '') {
$query .= ' AND cfnob.field_number_of_bedrooms_value >= '.$bedrooms.'';
}

if ($bathrooms != '') {
$query .= ' AND cth.field_number_of_bathrooms_value >= '.$bathrooms.'';
}
 
if (isset($sqFootMin) && is_numeric($sqFootMin) && $sqFootMin > 0) {
$query .= ' AND '.$sqFootMin.' <= cth.field_square_footage_value';
}

if (strlen($sqFootMax) && is_numeric($sqFootMax) && $sqFootMax > 0) {
$query .= ' AND '.$sqFootMax.' >= cth.field_square_footage_value';
}

$query .= ' ORDER BY cth.field_type_value, cfnob.field_number_of_bedrooms_value, n.title, cth.field_number_of_bathrooms_value';

$result = pager_query($query, 10);

$resultFromQuery = db_query($query);

$iHome = 0;

if (mysql_num_rows($resultFromQuery) >= 1) {
$output .= '<p>Your search returned <strong>'.mysql_num_rows($resultFromQuery).'</strong> result(s):</p>';

while ($iHome < 10) {
// layout code here for each result
}

$output .= theme('pager', NULL, 10);
return $output;

}

Pretty straightforward. This hooks into a search form and is called from a special page, searchresults.php, which is include() with php on specific pages.

==============
delaware web design
delaware website design

Not very secure

dwees - July 12, 2008 - 02:56

It looks like you are setting variables directly equal to GET and POST variables though and then directly injecting them into an SQL query. There must be a way to avoid doing that. I'd take a look at the Forms API so you don't need to inspect GET and POST directly, which helps with 'Cross site request forgery'. I'd also use placeholders for your SQL query (%d, %s, etc...) so that you aren't using user input directly in your sql query.

All someone needs to do is enter ?homeType=sql_injection;SELECT password FROM node WHERE uid = 1 and they'll have your admin password (hashed) and then use a rainbow table to look up your clear-text password. Even worse they could do ?homeType=sql_injection;DELETE * FROM node_revisions WHERE nid > 0 and delete all of your site content.

Dave

My site: http://www.unitorganizer.com/myblog

What is Forms

stripped your speech - July 12, 2008 - 19:06

What is Forms API?

I'm using Drupal 5.7.

==============
delaware web design
delaware website design

How do you use the

Blackguard - October 21, 2008 - 16:51

How do you use the placeholders inside a pager_query()?

EDIT: Nevermind - it's in the api. Same as good old db_query().

A comprehensive example

nazimrahman - August 29, 2008 - 13:16

You can find a comprehensive example at:

http://molecularsciences.org/drupal/drupal_paging

I'd like to see

NancyDru - August 29, 2008 - 14:01

I'd like to see your example meet Drupal coding standards. Also, with the simple query you are using, a count query is unnecessary.

Quick question: Does anyone

taqwa - October 5, 2008 - 22:02

Quick question: Does anyone know how I can number each results? For example, if the query yields 8000 results that are split into pages of 20, right now I would see this on each page:

Result 1
Result 2
Result 3
...
Result 20

and so on for all 400 page.
What I would like is for page one to display:

1. Result 1
2. Result 2
3. Result 3
....
20. Result 20

and then for page 2 to display:

21. Result 21
22. Result 22
22. Result 23
....
40. Result 40

and so on for all 400 pages.

If you're confused by what I mean, check www.reddit.com.

Any advice on how I can modify my SQL query would be greatly appreciated.

Well...

NancyDru - October 5, 2008 - 22:14

First you would have to render your list as an OL (which can be done with theme('item_list',...))The page function places a "page" query string in the URL, so it would be available in $_GET. You could then multiply that by the number of results per page and use that in the "start" attribute.

NancyDru (formerly Nancy W. until I got married to Drupal)

Is it possible to use this

neil.david - October 6, 2009 - 17:50

Is it possible to use this with 2 different tables in a page? if so, can anyone pls tell me how? thx so much

Yes, It's Possible to use Two Tables (or more) per Page

Mark in SC_USA - October 6, 2009 - 17:59

Look at the comments for the pager.inc file (in /includes folder).

To have more than one pager query per page assign each an $element value.

$rs = pager_query($query, $limit = 10, $element = 0, $count_query = NULL)

Your coding syntax may vary, but the $element tells Drupal which pager_query is which.

You can use 0 as your first $element value for the first pager_query, 1 for the next, and so on.

thx so much... that helped a

neil.david - October 6, 2009 - 18:53

thx so much... that helped a lot... which points me to another problem... is there a way to put anchors on the page numbers URL?

or I have to resort to make something with jQuery/javascript to make the page stay on the current scroll location. My tables could go way down the page in the future depending on content.

Not Sure About Anchors

Mark in SC_USA - October 6, 2009 - 19:00

Anchors are just html links to specific locations on a page, so you could insert them into your code. If you could explain why you want to do so, perhaps someone can give a nudge in the right direction.

Ok, my apologies for not

neil.david - October 6, 2009 - 19:22

Ok, my apologies for not explaining it fully.

Let me start by:

- I have put my tables in a block w/c is placed on the 'below content'(added block region) part of the page. The reason for this is because the other user that can access this page is only concerned on adding text content on the page. And doesn't know much on code.

- So, once the other user adds content my tables will go way down the page and it wouldn't be good if he/she would have to scroll down again and again when they click the next page of either tables.

Before, I did my tables with just php, it worked fine but wanted to take advantage of the drupal API. I am also new to Drupal, thanks so much for the help. I very much appreciate it.

No Worries

Mark in SC_USA - October 6, 2009 - 19:23

I'm also from a primarily php/mysql background, and am still getting used to Drupal's API. While I can't answer your question without some research, I'm sure someone will be along presently with some help.

Maintain Scroll Position of EVERY Element on PostBacks

neil.david - October 7, 2009 - 18:43

Hello,

After a few research, I have come across Mr. Mahdi Hasheminezhad's blog. He made a nice javascript plug-in, that solves my problem. Here is the URL to his blog : http://en.hasheminezhad.com/scrollsaver

Cheers!

 
 

Drupal is a registered trademark of Dries Buytaert.