I was wondering if anyone has experience using an already existing array of values with pager_query?

I wanted to display a list of information stored in an array. To get to the the information that I want to display, I've queried a table, stored the results to a temporary table, and sorted the array to get the data in a particular order. Since the info already exists in the array in the order I want to display it, the only thing left to do is try and print a paged display.

Here is what I've come up with so far to display the list, attempting to do so with a pager_query.

<?php

  $num_per_page = 15;
  $header = array('Lname', 'Fname', 'ID');

  //original query used to produce the $employee array
  $query = "SELECT * FROM temp_employee_data where 1";

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

  print theme('table', $header, $employee) . theme('pager', array(), $num_per_page);

This particular array has a list of 21 employees, and at the bottom of the list there is the pager information for 2 pages, which I would expect with a total of 21 employee records in the array.

However, all 21 employee records are printed to the screen, instead of just the first 15. When I click the links for the next page, I get all 21 displayed again, with the pager content indicating I'm on the 2nd page.

I think the root of the problem here is that pager_query isn't touching my $employee array, so it can't control how it's displayed.

Once again, any ideas or suggestions appreciated. Add yourself to the growing list of those rescuing me from my own programming skills!

Comments

mpruitt’s picture

I fully expect that as soon as I post this, someone else smarter than myself will share some code showing how to use an existing array with a pager_query.

Here is what I did.

1. Create a temporary Table to hold the data for the array.

2. Extract the data from the array into variables.

3. Write the value of the variables into the temporary table.

4. Normal, everyday pager_query against the temporary table to extract and page the results.

In doing some research I found that when you use a updated version of MySQL and PHP, the temporary table will be deleted as soon as the script finishes.

Pseudo Code:

<?php

// create temporary table
  $sql = "CREATE TEMPORARY TABLE temp_employee_data (
          fname VARCHAR(35) NOT NULL,
          lname VARCHAR(35) NOT NULL,
          id INT PRIMARY KEY
          )";
          
  $rs = db_query($sql);
  
  // write $employee into temporary table
  $i = 0;
  while ($i < $x){                         // $x appears much earlier in the code; it gets the COUNT of the $employee array
    $fname = $employee[$i]['fname'];
      $lname = $employee[$i]['lname'];
        $id = $employee[$i]['id'];
  
    $sql = "INSERT INTO temp_employee_data (fname, lname, id) VALUES ('%s', '%s', '%d')";
    $rs  = db_query($sql, $fname, $lname, $id);
    $i++;
          
  }
  $num_per_page = 15;
  
  $header = array('Fname', 'Lname', 'ID');
  $rows = array();
  
  $query = "SELECT * FROM temp_employee_data where 1";

  //pager_query function
  $rs = pager_query($query, $num_per_page);
  
  while ($data = db_fetch_object($rs)){
    $rows[] = array($data->fname, $data->lname, $data->id);
  }

  print theme('table', $header, $rows) . theme('pager', array(), $num_per_page);


andreyks’s picture

I have some problem. It's not simple way. Any other ideas?

andreyks’s picture

function listarray(array $arr) {
$output = '';

$count = count($arr); // количество эл-в
$page = isset($_GET['page']) ? $_GET['page'] : 0; // достаем с url номер pager
$limit = 2; // сколько элементов на страницу

// расчёты и вывод массива постранично
$max = ($page*$limit+$limit < $count) ? $page*$limit+$limit : $count;
for ($i=$page*$limit; $i<$max; $i++) {
$output .= ($i+1).') '.$arr[$i] . '



'; // выводим элемент, тематизация приветствуется.
}

global $pager_page_array, $pager_total; // тут пишем некоторые параметры для пейджера,
$pager_page_array = explode(',', $page); // в принципе "основной" момент функции,
$pager_total[0] = ceil($count/$limit); // остальное ерунда.

// вызываем тематизатор пейджера
$output .= theme('pager', NULL, $limit);

// возвращаем результат
return $output;
}

$arr = array(1,2,3,4,5,6,7,8,9,10,11); // готовим массив
echo listarray($ar) ;

mpruitt’s picture

Hey andreyks, I don't understand what you're trying to do in your code. Are you trying to display the contents of an array in a table or list?

cigotete’s picture

According to your question , (I think that) the snippet is a way to build a pagination to an array.

one note: in the last line:
echo listarray($ar) ;
change to:
echo listarray($arr) ;

and seems a different approach to: http://www.norio.be/blog/2008/07/reusing-drupals-pager-non-sql-data

vacilando’s picture

The script here achieves this perfectly in both Drupal 5 and Drupal 6.