Home » HTML » Pager » Manual
Data paging class which also builds links to the pages.
Introduction
Introduction – Usage of Pager 2.x
What is Pager?
Pager is a class to page an array of data. It is taken as input and it is paged according to various parameters. Pager also builds links within a specified range, and allows complete customization of the output (it even works with mod_rewrite). It is compatible with Pager v.1.x and Pager_Sliding API
Example 1
This simple example will page the array of alphabetical letters, giving back pages with 3 letters per page, and links to the previous two / next two pages:
<?php
require_once 'Pager.php';
$params = array(
'mode' => 'Jumping',
'perPage' => 3,
'delta' => 2,
'itemData' => array('a','b','c','d','e',[...omissis...],'z')
);
$pager = & Pager::factory($params);
$data = $pager->getPageData();
$links = $pager->getLinks();
//$links is an ordered+associative array with 'back'/'pages'/'next'/'first'/'last'/'all' links.
//NB: $links['all'] is the same as $pager->links;
//echo links to other pages:
echo $links['all'];
//Pager can also generate <link rel="first|prev|next|last"> tags
echo $pager->linkTags;
//Show data for current page:
echo 'PAGED DATA: ' ; print_r($data);
//Results from methods:
echo 'getCurrentPageID()...: '; var_dump($pager->getCurrentPageID());
echo 'getNextPageID()......: '; var_dump($pager->getNextPageID());
echo 'getPreviousPageID()..: '; var_dump($pager->getPreviousPageID());
echo 'numItems()...........: '; var_dump($pager->numItems());
echo 'numPages()...........: '; var_dump($pager->numPages());
echo 'isFirstPage()........: '; var_dump($pager->isFirstPage());
echo 'isLastPage().........: '; var_dump($pager->isLastPage());
echo 'isLastPageComplete().: '; var_dump($pager->isLastPageComplete());
echo '$pager->range........: '; var_dump($pager->range);
?>In case you're wondering, $pager->range is a numeric array; its keys are the numbers of the pages in the current range, and the matching values are booleans (TRUE if its key represents currentPage, FALSE otherwise). This array can be useful to build the links manually, e.g. when using a template engine.
Example 2
This example shows how you can use this class with mod_rewite. Let's suppose we have a .htaccess like this:
---------
RewriteEngine on
#Options FollowSymlinks
RewriteBase /
RewriteRule ^articles/([a-z]{1,12})/art([0-9]{1,4})\.html$ /article.php?num=$2&month=$1 [L]
---------
It should transform an url like "/articles/march/art15.html" into "/article.php?num=15&month=march"
<?php
require_once 'Pager.php';
$month = 'september';
$params = array(
'mode' => 'Sliding',
'append' => false,
'urlVar' => 'num',
'path' => 'http://myserver.com/articles/' . $month,
'fileName' => 'art%d.html', //Pager replaces "%d" with page number...
'itemData' => array('a','b','c',[...omissis...],'z'),
'perPage' => 3
);
$pager = & Pager::factory($params);
$data = $pager->getPageData();
echo $pager->links;
echo 'Data for current page: '; print_r($data);
?>
More pagers in a single page
Using more than one pager in a single page is as simple as using a different
urlVar for each pager:
<?php
require_once 'Pager.php';
//first pager
$params1 = array(
'perPage' => 3,
'urlVar' => 'pageID_articles', //1st identifier
'itemData' => $someArray
);
$pager1 = & Pager::factory($params1);
$data1 = $pager1->getPageData();
$links1 = $pager1->getLinks();
//second pager
$params2 = array(
'perPage' => 8,
'urlVar' => 'pageID_news', //2nd identifier
'itemData' => $someOtherArray
);
$pager2 = & Pager::factory($params2);
$data2 = $pager2->getPageData();
$links2 = $pager2->getLinks();
?>
Pager and big db resultsets
If you want to paginate db resultsets, fetching them all into an array and passing it to Pager might not be the best option. You can still leverage Pager and have good performances using a wrapper. There is a sample wrapper for each one of the PEAR db abstraction systems in the /examples/ dir of the package. You may use it as-is or customize it to your needs.
Adding extra variables to the querystring
If you need to add some extra variables to the querystring,
use the extraVars parameter:
<?php
$params = array(
'extraVars' => array(
'firstKey' => 'firstValue',
'secondKey' => 'secondValue',
//...
),
//...
);
$pager1 = & Pager::factory($params);
?>
Important note for PHP 5 users
Since version 2.2.1, Pager works with PHP 5 too, but you must use the factory() method instead of the constructor (which is deprecated):
<?php
require_once 'Pager.php';
//wrong:
//$pager =& new Pager($params);
//right
$pager =& Pager::factory($params);
//continue as you did before
?>
If you are using a previous revision and cannot update, you must write the following code on PHP 5:
<?php
//chose your preferred mode [Jumping | Sliding]:
//require_once 'Pager/Jumping.php';
require_once 'Pager/Sliding.php';
//$pager =& new Pager_Jumping($params);
$pager =& new Pager_Sliding($params);
//continue as you did before
?>
Pager Tutorials
There are some other online resources with in-depth coverage of what Pager can do: PEAR::Pager tutorials.
- How to efficiently paginate database results
- Create pretty links with Pager and mod_rewrite
- Navigation with Pager and AJAX (or simple Javascript)
- Article pagination, or how to navigate through the paragraphs with Pager
- Two examples: Paginate db results with Pager_Wrapper and display them with AJAX. Use Pager with the Smarty template engine.
Pager "Jumping" vs. "Sliding"
Pager "Jumping" vs. "Sliding" – Feature comparison of the two pager styles
What are the differences between the two styles?
Since an example is worth 1000 words:
"Jumping" Pager logic
Let's suppose that the data spans on 15 pages, and the window width is 5 page links. The links are built on "frames" of 5 pages each: [1-5] [6-10] [11-15] Pager in "Jumping" mode always shows the same 5 page links while you are on one of these pages. Here's a temporal succession of the links, starting from page 1 and moving forward. There are brakets around current page number to highlight this:
<?php
a) {1} 2 3 4 5 => // first frame: [1-5]
b) <= 1 {2} 3 4 5 =>
c) <= 1 2 {3} 4 5 =>
d) <= 1 2 3 {4} 5 =>
e) <= 1 2 3 4 {5} => // HERE IT JUMPS TO THE NEXT FRAME
f) <= {6} 7 8 9 10 => // second frame: [6-10]
g) <= 6 {7} 8 9 10 =>
h) <= 6 7 {8} 9 10 =>
?>and so on. See what a "jumping window" frame is? When you reach a limit (in the example, you go from page 5 to page 6), it "jumps" to next frame (links from page 6 to 10).
"Sliding" Pager logic
Instead of jumping from one frame to the other, with Pager in "Sliding" mode the change is done smoothly, and the current page is always shown at the center of the "window" (except of course for the first and the last pages):
<?php
a) {1} 2 3 4 5 => [15]
b) [1] <= 1 {2} 3 4 5 => [15]
c) [1] <= 1 2 {3} 4 5 => [15] // HERE IT's STARTING WORKING AS DESIGNED
d) [1] <= 2 3 {4} 5 6 => [15] // see: current page number is at the center of the window
e) [1] <= 3 4 {5} 6 7 => [15] // and it stays there...
f) [1] <= 4 5 {6} 7 8 => [15]
g) [1] <= 5 6 {7} 8 9 => [15]
h) [1] <= 6 7 {8} 9 10 => [15]
?>and so on.
Other differences
Apart from the different "philosophy", there is one difference in the
delta parameter: in "Jumping" mode, it's the
number of page numbers to show; in "Sliding" mode it's the number of
page numbers to show before and after the current one.
Pager::factory
Pager::factory() – Creates a pager instance
Synopsis
require_once 'Pager.php';
object &factory (
array $options
)
Parameter
Pager::factory() method takes an associative array of parameters as input values. This is the complete list of these options:
-
itemData[array] Array of items to page. -
totalItems[integer] Number of items to page (used only ifitemDatais not provided). -
perPage[integer] Number of items to display on each page. -
delta[integer] Number of page numbers to display before and after the current one. -
mode[string] "Jumping" or "Sliding" -window - It determines pager behaviour. -
httpMethod[string] Specifies the HTTP method to use. Valid values are 'GET' or 'POST'. -
formID[string] Specifies which HTML form to use in POST mode. -
importQuery[boolean] if true (default behaviour), variables and values are imported from the submitted data (query string) and used in the generated links, otherwise they're ignored completely -
currentPage[integer] Initial page number (if you want to show page #2 by default, setcurrentPageto 2) -
expanded[boolean] if TRUE, window size is always 2*delta+1 -
linkClass[string] Name of CSS class used for link styling. -
urlVar[string] Name of URL var used to indicate the page number. Default value is "pageID". -
path[string] Complete path to the page (without the page name). -
fileName[string] name of the page, with a "%d" ifappend== TRUE. -
fixFileName[boolean] If set to FALSE, thefileNameoption is not overridden. Use at your own risk. -
append[boolean] If TRUE pageID is appended as GET value to the URL. If FALSE it is embedded in the URL according tofileNamespecs. -
altFirst[string] Alt text to display on the link of the first page. Default value is "first page"; if you want a string with the page number, use "%d" as a placeholder (for instance "page %d") -
altPrev[string] Alt text to display on the link of the previous page. Default value is "previous page"; -
altNext[string] Alt text to display on the link of the next page. Default value is "next page"; -
altLast[string] Alt text to display on the link of the last page. Default value is "last page"; if you want a string with the page number, use "%d" as a placeholder (for instance "page %d") -
altPage[string] Alt text to display before the page number. Default value is "page " (followed by the page number). You can optionally use "%d" as a placeholder (for instance "page n. %d") to place the page number where you want. -
prevImg[string] Something to display instead of "<<". It can be text such as "<< PREV" or an <img/> as well. -
nextImg[string] Something to display instead of ">>". It can be text such as "NEXT >>" or an <img/> as well. -
separator[string] What to use to separate numbers. It can be an <img/>, a comma, an hyphen, or whatever. -
spacesBeforeSeparator[integer] Number of spaces before the separator. -
spacesAfterSeparator[integer] Number of spaces after the separator. -
firstLinkTitle[string] String used as title in <link rel="first"> tag -
nextLinkTitle[string] String used as title in <link rel="next"> tag -
prevLinkTitle[string] String used as title in <link rel="previous"> tag -
lastLinkTitle[string] String used as title in <link rel="last"> tag -
curPageLinkClassName[string] CSS class name for the current page link. -
curPageSpanPre[string] Text before the current page link. -
curPageSpanPost[string] Text after the current page link. -
firstPagePre[string] String used before the first page number. It can be an <img/>, a "{", an empty string, or whatever. -
firstPageText[string] String used in place of the first page number. -
firstPagePost[string] String used after the first page number. It can be an <img/>, a "}", an empty string, or whatever. -
lastPagePre[string] Similar tofirstPagePre, but used for last page number. -
lastPageText[string] Similar tofirstPageText, but used for last page number. -
lastPagePost[string] Similar tofirstPagePost, but used for last page number. -
clearIfVoid[boolean] if there's only one page, don't display pager links (returns an empty string). -
extraVars[array] additional URL vars to be added to the querystring. -
excludeVars[array] URL vars to be excluded from the querystring. -
useSessions[boolean] if TRUE, number of items to display per page is stored in the $_SESSION[$_sessionVar] var. -
closeSession[boolean] if TRUE, the session is closed just after R/W. -
sessionVar[string] Name of the session var for perPage value. A value different from default can be useful when using more than one Pager istance in the page. -
showAllText[string] Text to be used for the 'show all' option in the select box generated by getPerPageSelectBox() -
pearErrorMode[constant] PEAR_ERROR mode for raiseError(). Default is PEAR_ERROR_RETURN.
REQUIRED options are:
-
fileNameIFappend==FALSE (default is TRUE) -
itemDataORtotalItems(if itemData is set, totalItems is overwritten)
Return value
object - a specific Pager instance
or a PEAR_Error object, if fails
Pager::setOptions
Pager::setOptions() – Set or change option after the Pager object has been constructed
Synopsis
require_once 'Pager.php';
array Pager::setOptions (
array $options
)
Description
Remember to call build() after this method to regenerate the data and the links.
Parameter
-
integer $index- an associative array of options. See Pager::factory() for the full list of options.
Return value
return PAGER_OK constant on success
Pager::build
Pager::build() – Generate or refresh the links and paged data after a call to setOptions()
Synopsis
require_once 'Pager.php';
array Pager::build (
)
Description
- If you want to change an option after the Pager object has been constructed, after the call to setOptions() you have to generate or refresh the links and paged data with this method.
Pager::getCurrentPageID
Pager::getCurrentPageID() – Returns current page number
Synopsis
require_once 'Pager.php';
integer getCurrentPageID (
)
Return value
integer - Current page number.
Pager::getLinks
Pager::getLinks() – Returns back/next/first/last and page links, both as ordered and associative array.
Synopsis
require_once 'Pager.php';
array Pager::getLinks (
integer $pageID
= null
)
Parameter
-
integer
$pageID- Optional pageID. If specified, linksfor that page are provided instead of current one.
Return value
return back/pages/next/first/last/all links, both as numeric and associative array.
Pager::getNextPageID
Pager::getNextPageID() – Returns next page number.
Synopsis
require_once 'Pager.php';
mixed Pager::getNextPageID (
)
Description
If current page is last page this function returns FALSE, otherwise returns next page number.
Return value
return Next page number or FALSE
Pager::getOffsetByPageId
Pager::getOffsetByPageId() – Returns offsets for given pageID.
Synopsis
require_once 'Pager.php';
array Pager::getOffsetByPageId (
integer $pageid
= null
)
Description
Returns offsets for given pageID.
Eg, if you pass it pageID one and your
perPage limit is 10 it will return (1, 10).
pageID=2 would give you (11, 20).
if the method is called without parameter, pageID is set to currentPage
Parameter
-
integer $pageid- PageID to get offsets for
Return value
return array with first and last offsets
Deprecated
deprecated
Pager::getPageData
Pager::getPageData() – Returns an array of current pages data
Synopsis
require_once 'Pager.php';
array Pager::getPageData (
integer $pageID
= null
)
Parameter
-
integer $pageID- Desired page ID (optional)
Return value
return array of data for this page.
Pager::getPageIdByOffset
Pager::getPageIdByOffset() – Returns the page number for the given offset
Synopsis
require_once 'Pager.php';
array Pager::getPageIdByOffset (
integer $index
)
Description
This method is only available in "Jumping" mode.
Parameter
-
integer $index- Offset to get pageID for
Return value
return Page number for this offset
Pager::getPageRangeByPageId
Pager::getPageRangeByPageId() – Returns offsets for given pageID.
Synopsis
require_once 'Pager.php';
array Pager::getPageRangeByPageId (
integer $pageid
= null
)
Description
Given a PageId, it returns the limits of the range of pages displayed. While getOffsetByPageId() returns the offset of the data within the current page, this method returns the offsets of the page numbers interval.
E.g., in "Jumping" mode, if you have pageId=3 and
delta=10, it will return (1, 10).
pageID=8 would give you (1, 10) as well, because
1 <= 8 <= 10.
pageID=11 would give you (11, 20).
In "Sliding" mode, if you have pageId=5 and
delta=2, it will return (3, 7).
pageID of 9 would give you (4, 8).
if the method is called
without parameter, pageID is set to currentPage number
Parameter
-
integer $pageid- PageID to get offsets for
Return value
return array with first and last offsets
Pager::getPageSelectBox
Pager::getPageSelectBox() – Returns a string with a XHTML SELECT menu, to choose the page to display.
Synopsis
require_once 'Pager.php';
array Pager::getPageSelectBox (
array $params
, string $extraAttributes = ''
)
Parameter
-
array $params(optional)-
'optionText': text to show in each option. Use '%d' where you want to see the number of the page. -
'autoSubmit': if true, add some js code to submit the form on the onChange event
-
-
string $extraAttributes(html attributes) Tag attributes or HTML attributes (id="foo" pairs), will be inserted in the <select> tag.
Description
Returns a string with a XHTML SELECT menu with the page numbers, useful as an alternative to the links
Example
This example shows how you can create a select box to let your users choose the number of the page to go to.
<?php
include 'Pager.php';
$params = array(
'mode' => 'Jumping',
'perPage' => 3,
'delta' => 2,
'itemData' => array('a','b','c','d','e',[...omissis...],'z'),
);
$pager = & Pager::factory($params);
$selectBoxParams = array(
'optionText' => 'page %d',
'autoSubmit' => true,
);
$selectBox = $pager->getPageSelectBox();
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="GET">';
echo $selectBox;
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Return value
return string with the XHTML SELECT menu.
Pager::getPreviousPageID
Pager::getPreviousPageID() – Returns previous page number.
Synopsis
require_once 'Pager.php';
mixed Pager::getPreviousPageID (
)
Description
If current page is first page this function returns FALSE, otherwise returns previous page number.
Return value
return Previous page number or FALSE.
Pager::getPerPageSelectBox
Pager::getPerPageSelectBox() – Returns a string with a XHTML SELECT menu, to choose how many items per page should be displayed.
Synopsis
require_once 'Pager.php';
array Pager::getPerPageSelectBox (
integer $start = 5
, integer $end = 30
, integer $step = 5
, boolean $showAllData = false
, string $optionText = '%d'
)
Parameter
-
integer $start- Min. number of items per page (optional) -
integer $end- Max. number of items per page (optional) -
integer $step- Increment between two options (optional) -
boolean $showAllData- If true, perPage is set equal to totalItems (optional) -
array $extraParams(optional)-
'optionText': text to show in each option. Use '%d' where you want to see the number of pages selected. -
'attributes': (html attributes) Tag attributes or HTML attributes (id="foo" pairs), will be inserted in the <select> tag. -
'checkMaxLimit': if true, Pager checks if $end is bigger than $totalItems, and doesn't show the extra select options.
-
Description
Returns a string with a XHTML SELECT menu, useful for letting the user choose
how many items per page should be displayed. If parameter
useSessions is TRUE, this value is stored in
a session var. The string isn't echoed right away so you can use it
with template engines.
Example
This example shows how you can create a select box to let your users choose the number of items to display on each page.
<?php
include 'Pager/Pager.php';
$params = array(
'mode' => 'Jumping',
'perPage' => 3,
'delta' => 2,
'itemData' => array('a','b','c','d','e',[...omissis...],'z')
);
$pager = & Pager::factory($params);
$selectBox = $pager->getPerPageSelectBox();
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="GET">';
echo $selectBox;
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Return value
return string with the XHTML SELECT menu.
Pager::isFirstPage
Pager::isFirstPage() – Returns whether current page is first page
Synopsis
require_once 'Pager.php';
bool Pager::isFirstPage (
)
Return value
return TRUE or FALSE, wrt it is the first page or not.
Pager::isLastPage
Pager::isLastPage() – Returns whether current page is last page
Synopsis
require_once 'Pager.php';
bool Pager::isLastPage (
)
Return value
return TRUE or FALSE, wrt it is the last page or not.
Pager::isLastPageComplete
Pager::isLastPageComplete() – Returns whether last page is complete
Synopsis
require_once 'Pager.php';
bool Pager::isLastPageComplete (
)
Return value
return TRUE or FALSE, wrt the last page is complete
(i.e. it has perPage values in the array for the last
page) or not.
Pager::numItems
Pager::numItems() – Returns number of items
Synopsis
require_once 'Pager.php';
int Pager_Sliding::numItems (
)
Return value
return integer - Number of items
Pager::numPages
Pager::numPages() – Returns number of pages
Synopsis
require_once 'Pager.php';
int Pager_Sliding::numPages (
)
Return value
return integer - Number of pages
Pager::Pager
Pager::Pager() – Creates a pager instance
Synopsis
require_once 'Pager.php';
object &Pager (
array $options
)
Deprecated
The constructor is deprecated in favour of the new factory() method, which is PHP5 compatible too.
Parameter
Pager constructor takes an associative array of parameters as input values. This is the complete list of these options:
-
itemData[array] Array of items to page. -
totalItems[integer] Number of items to page (used only ifitemDatais not provided). -
perPage[integer] Number of items to display on each page. -
delta[integer] Number of page numbers to display before and after the current one. -
mode[string] "Jumping" or "Sliding" -window - It determines pager behaviour. -
expanded[boolean] if TRUE, window size is always 2*delta+1 -
linkClass[string] Name of CSS class used for link styling. -
urlVar[string] Name of URL var used to indicate the page number. Default value is "pageID". -
path[string] Complete path to the page (without the page name). -
fileName[string] name of the page, with a "%d" ifappend== TRUE. -
append[boolean] If TRUE pageID is appended as GET value to the URL. If FALSE it is embedded in the URL according tofileNamespecs. -
altPrev[string] Alt text to display for prev page, on prev link. Default value is "previous page"; -
altNext[string] Alt text to display for next page, on next link. Default value is "next page"; -
altPage[string] Alt text to display before the page number. Default value is "page ". -
prevImg[string] Something to display instead of "<<". It can be text such as "<< PREV" or an <img/> as well. -
nextImg[string] Something to display instead of ">>". It can be text such as "NEXT >>" or an <img/> as well. -
separator[string] What to use to separate numbers. It can be an <img/>, a comma, an hyphen, or whatever. -
spacesBeforeSeparator[integer] Number of spaces before the separator. -
spacesAfterSeparator[integer] Number of spaces after the separator. -
firstPagePre[string] String used before first page number. It can be an <img/>, a "{", an empty string, or whatever. -
firstPageText[string] String used in place of first page number. -
firstPagePost[string] String used after first page number. It can be an <img/>, a "}", an empty string, or whatever. -
lastPagePre[string] Similar tofirstPagePre, but used for last page number. -
lastPageText[string] Similar tofirstPageText, but used for last page number. -
lastPagePost[string] Similar tofirstPagePost, but used for last page number. -
curPageLinkClassName[string] Name of CSS class used for current page link. -
clearIfVoid[boolean] if there's only one page, don't display pager (returns an empty string). -
useSessions[boolean] if TRUE, number of items to display per page is stored in the $_SESSION[$_sessionVar] var. -
closeSession[boolean] if TRUE, the session is closed just after R/W. -
sessionVar[string] Name of the session var for perPage value. A value different from default can be useful when using more than one Pager istance in the page. -
pearErrorMode[constant] PEAR_ERROR mode for raiseError(). Default is PEAR_ERROR_RETURN.
REQUIRED options are:
-
fileNameIFappend==FALSE (default is TRUE) -
itemDataORtotalItems(if itemData is set, totalItems is overwritten)
Return value
object - a specific Pager instance
or a PEAR_Error object, if fails