Skip to content

Using pagination to navigate through results

AlexandreToyer edited this page Mar 14, 2014 · 6 revisions

It is easy to create a pagination with the OssPaging class.

Let's start with the example code from our page explaining a basic query..

We will need to improve this code by adding:

  • a way to get the current page from the URL;
  • an "offset" in the query to OpenSearchServer, so it can return the appropriate documents;
  • display of the pagination links.

Let's write this code:

require_once(dirname(__FILE__).'/oss_api.class.php');
require_once(dirname(__FILE__).'/oss_results.class.php');
require_once(dirname(__FILE__).'/oss_paging.class.php'); //requires the OssPaging class

$oss_url = 'http://localhost:9090';
$oss_index = 'my_index';
$oss_login = 'my_login';
$oss_key = '54a51de4f27cefbcb7a771335b980567f'
$oss_api = new OssApi($oss_url, $oss_index, $oss_login, $oss_key);

$xmlResult = $oss_search->query('open')
                        ->lang('en')
                        ->template('search')
                        ->filter('date:[* TO *]')
                        ->negativeFilter('visibility:0') 
                        ->rows(10)
                        ->execute(60);

$oss_result = new OssResults($xmlResult);        
$doc_found_number = min(
          $this->oss_result->getResultRows(), 
          $this->oss_result->getResultFound() - $this->oss_result->getResultCollapsedCount() - $startOffset
       );

$results = array();
for ($i = 0; $i < $doc_found_number; $i++) {
  $pos = $oss_result->getResultRows() + $i;
  $title = $oss_result->getField($pos, 'title');
  $categories = $oss_result->getField($pos, 'category', false, false, null, true);
  $results[] = array('title' => $title, 'categories' => $categories);
}

print '<ul>';
foreach($results as $result) {
  $categories = is_array($result['categories'])) ? implode(', ', $result['categories']) : $result['categories'];
  print '<li>'.$result['title'].' - <em>'.$categories.'</em></li>';
}
print '</ul>';

Clone this wiki locally