Location: PHPKode > scripts > Pagination optimized > pagination-optimized/pagination_class.php
<?php
//Pagination Class
// 15.03.2008
// by Murat BIYIKLI
//if you want to understand these codes, read it in a wide screen
/* Usage !---------------->

//important info for database functions used in this class:
I used a class for 4 Mysql Functions, you may need to replace them according to your application or re-create them. 
	$GLOBALS[CLASS_DB]->pc_db_query($sql_query);	refers to function mysql_query($sql_query)
	$GLOBALS[CLASS_DB]->pc_db_num_rows($result);	refers to function mysql_num_rows($result)
	$GLOBALS[CLASS_DB]->pc_db_fetch_row($result);	refers to function mysql_fetch_row($result)
	$GLOBALS[CLASS_DB]->pc_db_free_result($result);	refers to function mysql_free_result($result)
and I assumed that you already have connected to a database
//end info for database functions

//Lets Call class
include_once('pagination_class.php');
$CLASS_PAGINATION = new Pagination;

//define initial limits
$CLASS_PAGINATION->Def_WorkingScriptName = '';  // forex: search.php
$CLASS_PAGINATION->Def_RecordNumberPerPage = 10; 
$CLASS_PAGINATION->Def_Sql_LimitMaxCount = 3000;
$CLASS_PAGINATION->Def_MaxRecordNumberPerPage = 100;
$CLASS_PAGINATION->Def_MaxPageLinkNumberInLinkSequence = 19;
$CLASS_PAGINATION->Def_Bool_LinksRequired = true;  //if you want a page link list like 1 2 3 4 ..


//define language translations
$CLASS_PAGINATION->Def_Html_Link_PreviousText = "Previous"; 
$CLASS_PAGINATION->Def_Html_Link_NextText = "Next"; 
$CLASS_PAGINATION->Def_Html_NoResultText = "No New Results Found!";
$CLASS_PAGINATION->Def_Html_InTotalPagesText = "In total pages";
$CLASS_PAGINATION->Def_Html_TotalPagesFoundText = "Total pages found";
$CLASS_PAGINATION->Def_Html_RecordsText = "Records";
$CLASS_PAGINATION->Def_Html_CurrentPageText "Current page is";

//define parameters to use - not necessary to define defaults 
$CLASS_PAGINATION->Def_CurrentPageLinkParameterVar = 'p'; 
$CLASS_PAGINATION->Def_RecordNumberLinkParameterVar = 'r'; 
$CLASS_PAGINATION->Def_SearchLinkParameterVar = 's'; 

//define sql queries
$CLASS_PAGINATION->Get_Sql_QueryWhereCondition='';
$CLASS_PAGINATION->Def_Sql_ForPagination = 'SELECT * FROM forum WHERE 1 '.$CLASS_PAGINATION->Get_Sql_QueryWhereCondition.' ORDER BY id DESC ';
$CLASS_PAGINATION->Def_Sql_ForCountRecords = 'SELECT id FROM forum WHERE 1 '.$CLASS_PAGINATION->Get_Sql_QueryWhereCondition;

//define extra parameters to links
$CLASS_PAGINATION->Get_Link_UrlExtraParameters='';

//call main Functions
$CLASS_PAGINATION->PaginationProgress();

//At last you get:
$CLASS_PAGINATION->Gener_Sql_ForPagination
$CLASS_PAGINATION->Gener_Html_TotalRecordsandLinks
$CLASS_PAGINATION->Gener_Sql_LimitForPagination

//use this Gener_Sql_ForPagination to query and show results in a limited way.
//use links to paginate your results anywhere on your result page.

------------------------------*/

class Pagination
{
	var $Get_Link_UrlExtraParameters;
	var $Def_RecordNumberPerPage;
	var $Def_MaxRecordNumberPerPage;
	var $Def_WorkingScriptName;
	var $Get_SearchPhrase;
	var $Get_CurrentPage;
	var $Get_RecordNumberPerPage;
	var $Def_Sql_ForPagination;
	var $Def_Sql_ForCountRecords;
	var $Def_Sql_LimitMaxCount;
	var $Def_MaxPageLinkNumberInLinkSequence;
	var $Def_Html_Link_PreviousText; 
	var $Def_Html_Link_NextText; 
	var $Def_Html_NoResultText;
	var $Def_Html_InTotalPagesText;
	var $Def_Html_TotalPagesFoundText;
	var $Def_Html_RecordsText;
	var $Def_Html_CurrentPageText;
	var $Def_CurrentPageLinkParameterVar;  // value: p like: search.php?p=12
	var $Def_RecordNumberLinkParameterVar;  // value: r like: search.php?p=12&r=50
	var $Def_SearchLinkParameterVar;  // value: s like: search.php?p=12&r=50&s=keyword
	var $Get_Sql_QueryWhereCondition;
	var $Calculated_TotalRowsNum;
	var $Gener_Sql_ForPagination;
	var $Gener_Sql_LimitForPagination;
	var $Gener_Html_Links;
	var $Gener_Html_TotalRecordsInfo;
	var $Gener_Html_TotalRecordsandLinks;
	var $Gener_Html_ReturnMessage;
	var $Def_Css_TotalRecordsandLinksTableTd;
	var $Def_Css_NumLinks;

   /* Class constructor */
	function Pagination() {

		//initializing vars for security
		settype($this->Get_CurrentPage, 'integer');
		settype($this->Def_MaxRecordNumberPerPage, 'integer');
		settype($this->Def_RecordNumberPerPage, 'integer');
		settype($this->Get_RecordNumberPerPage, 'integer');

		//default values
		$this->Def_Html_Link_PreviousText = "Previous"; 
		$this->Def_Html_Link_NextText = "Next"; 
		$this->Def_Html_NoResultText = "No New Results Found!"; 
		$this->Def_Html_InTotalPagesText = "In total pages";
		$this->Def_Html_TotalPagesFoundText = "Total pages found";
		$this->Def_Html_RecordsText = "Records";
		$this->Def_Html_CurrentPageText = "Current page is";

		$this->Def_CurrentPageLinkParameterVar = 'p'; 
		$this->Def_RecordNumberLinkParameterVar = 'r'; 
		$this->Def_SearchLinkParameterVar = 's';

		$this->Get_Link_UrlExtraParameters = '';
		$this->Get_SearchPhrase = '';

		$this->Def_WorkingScriptName = '';
		$this->Def_RecordNumberPerPage = 5; 
		$this->Def_Sql_LimitMaxCount = 3000;
		$this->Def_MaxRecordNumberPerPage = 100;
		$this->Def_MaxPageLinkNumberInLinkSequence = 10;
		$this->Def_Bool_LinksRequired = true;  //if you want a page link list like 1 2 3 4 ..

		Return true; 

	}//end func Pagination


	//generating sql limited
	function PaginationProgress(){
		
		//Getting definiton for current page parameter for url link to result pages	
		if(!isset($this->Def_CurrentPageLinkParameterVar)){
			$this->Def_CurrentPageLinkParameterVar='p';
		}
		if(!isset($this->Def_RecordNumberLinkParameterVar)){
			$this->Def_RecordNumberLinkParameterVar='r';
		}
		if(!isset($this->Def_SearchLinkParameterVar)){
			$this->Def_SearchLinkParameterVar='s';
		}

		if(!isset($this->Def_Css_TotalRecordsandLinksTableTd)) {
			$this->Def_Css_TotalRecordsandLinksTableTd='paginTd';
		}

		if(!isset($this->Def_Css_NumLinks)) {
			$this->Def_Css_NumLinks='Pgn';
		}		
		
		//Getting current page from url parameters
		if( isset($_REQUEST[$this->Def_CurrentPageLinkParameterVar]) ) {
			$this->Get_CurrentPage = intval($_REQUEST[$this->Def_CurrentPageLinkParameterVar]);
		}

		//Initializing current page number
		if (!isset($this->Get_CurrentPage) || $this->Get_CurrentPage <= 0 ){
			$this->Get_CurrentPage = 1;
		}

		//Getting search phrase from request if any and also putting them on the link squence
		if( isset($_REQUEST[$this->Def_SearchLinkParameterVar]) && trim($_REQUEST[$this->Def_SearchLinkParameterVar]!="") ) {
			$this->Get_SearchPhrase = stripslashes($_REQUEST[$this->Def_SearchLinkParameterVar]);
			$this->Get_Link_UrlExtraParameters = "&".$this->Def_SearchLinkParameterVar."=".$this->Get_SearchPhrase.$this->Get_Link_UrlExtraParameters;
		}

		//how many max records set to show per page by site admin		
		//Setting default limit per page if not set or wrong set
		if(!isset($this->Def_MaxRecordNumberPerPage) || intval($this->Def_MaxRecordNumberPerPage<=0) ||  $this->Def_MaxRecordNumberPerPage>1000) {
				$this->Def_MaxRecordNumberPerPage = 100; // Limit per page 
		}

		//how many records set to show per page by site admin		
		//Setting default limit per page if not set or wrong set
		if(!isset($this->Def_RecordNumberPerPage) || intval($this->Def_RecordNumberPerPage<=0) ||  $this->Def_RecordNumberPerPage>1000) {
			$this->Def_RecordNumberPerPage = 20; // Limit per page 
		}

		//how many records to show per page by user selection
		if( isset($_REQUEST[$this->Def_RecordNumberLinkParameterVar]) ) {
			$this->Get_RecordNumberPerPage = intval($_REQUEST[$this->Def_RecordNumberLinkParameterVar]);
			if($this->Get_RecordNumberPerPage > $this->Def_MaxRecordNumberPerPage) {
				$this->Get_RecordNumberPerPage = $this->Def_RecordNumberPerPage;
			}
		}else {
			$this->Get_RecordNumberPerPage = $this->Def_RecordNumberPerPage;	
		}

		//how many records to show per page limited if illegal number of record requested
		if($this->Get_RecordNumberPerPage <=0 || $this->Get_RecordNumberPerPage > $this->Def_MaxRecordNumberPerPage ){
			$this->Get_RecordNumberPerPage = $this->Def_RecordNumberPerPage;
		}

		if(!isset($this->Get_Sql_QueryWhereCondition)) {
			$this->Get_Sql_QueryWhereCondition='';
		}
				
		//TOTAL NUMBER OF ROWS
		//Getting total row number from database
		//Initializing record counting sql for a general limit for query results and pages , if Def_Sql_LimitMaxCount is equal to zero (0), query is not limited!
		if(isset($this->Def_Sql_LimitMaxCount) && $this->Def_Sql_LimitMaxCount!=0 && isset($this->Def_Sql_ForCountRecords) ){
			$this->Def_Sql_ForCountRecords.=" LIMIT ".intval($this->Def_Sql_LimitMaxCount)." ";
		}
		//Query for counting total record number (num rows)
		if(!$result = $GLOBALS[CLASS_DB]->pc_db_query($this->Def_Sql_ForCountRecords)){
			//if No result found, html text to return:
			$this->Gener_Html_ReturnMessage = $this->Def_Html_NoResultText; 
			$totalRowsNum=0;
		}else {
			//whether to select count id or select a limited id, if large database then use second choice
			if($this->Def_Sql_LimitMaxCount){
				//if an sql like 'select id from .. where ..' is used:
				$totalRowsNum = $GLOBALS[CLASS_DB]->pc_db_num_rows($result); // total num rows of count sql 
			}else{
				//if an sql like 'select count(id) as count from .. where ..' is used:
				$countrowArr=$GLOBALS[CLASS_DB]->pc_db_fetch_row($result);
				$totalRowsNum = $countrowArr[0]; // total num rows is the first element of the returned array of count sql query result
			}

			//SQL FINAL or NO RESULTS
			if(!$totalRowsNum){
				$this->Gener_Html_ReturnMessage = $this->Def_Html_NoResultText;
				$this->Gener_Sql_LimitForPagination = " LIMIT ".$this->Get_RecordNumberPerPage*($this->Get_CurrentPage-1).", ".$this->Get_RecordNumberPerPage;
				$this->Gener_Sql_ForPagination = $this->Def_Sql_ForPagination.$this->Gener_Sql_LimitForPagination;
			}else {
				//sql limitation generation for any func outer (OUTPUT)
				$this->Gener_Sql_LimitForPagination = " LIMIT ".$this->Get_RecordNumberPerPage*($this->Get_CurrentPage-1).", ".$this->Get_RecordNumberPerPage;
				$this->Gener_Sql_ForPagination = $this->Def_Sql_ForPagination.$this->Gener_Sql_LimitForPagination;
				
			}//endif
		}//endif
		$GLOBALS[CLASS_DB]->pc_db_free_result($result);
		$this->Calculated_TotalRowsNum = $totalRowsNum;
		
		if($this->Def_Bool_LinksRequired) {
			$this->PaginationLinks(); //call and return $this->Gener_Html_TotalRecordsandLinks
		}
		return true;

	}//end func PaginationProgress


	//links squence
	function PaginationLinks(){		
		
		if ($this->Calculated_TotalRowsNum <= $this->Get_RecordNumberPerPage ) { 
			 //If the number of returned is less than the limit, show nothing
		}else{
			//Divide total rows by record limit to get the number of pages
			$totalCalculatedPages = ceil($this->Calculated_TotalRowsNum/$this->Get_RecordNumberPerPage);
			
			//LINK SQUENCE
			//If pages found exceeds the limit of links squence
			if( $totalCalculatedPages > $this->Def_MaxPageLinkNumberInLinkSequence ) {
				//finding the number of the links before the current page
				$lowlim=$this->Get_CurrentPage-intval($this->Def_MaxPageLinkNumberInLinkSequence/2);
				//finding the number of the links after the current page
				$toplim=$this->Get_CurrentPage+intval($this->Def_MaxPageLinkNumberInLinkSequence/2);
				if($lowlim<=0) {
					$lowlim=1;
					$toplim=$this->Def_MaxPageLinkNumberInLinkSequence;
				}
				if($toplim>$totalCalculatedPages) {
					$toplim=$totalCalculatedPages;
					$lowlim=$totalCalculatedPages-$this->Def_MaxPageLinkNumberInLinkSequence;
				}
				//page link squence html generation by function
				$this->Gener_Html_Links = $this->PaginationNumericLinks($lowlim,$toplim);
				//extending the next links by dots
				if($toplim < $totalCalculatedPages) {
					$this->Gener_Html_Links.= "...";
				}
				//extending the prev links by dots
				if($lowlim>1) {
					$this->Gener_Html_Links = "...".$this->Gener_Html_Links; 
				}
			//If pages found not exceeds the limit of links squence
			}else {
				//page link squence html generation by function beginning from 1
				$this->Gener_Html_Links = $this->PaginationNumericLinks(1,$totalCalculatedPages);
			}//endif

			//PREVIOUS LINK
			//page links for previous and next page links after and before link squence
			//If the current page is not equal to 1, Show the link. Else (if>1) show just text
			if ($this->Get_CurrentPage!=1) { 
				$prevOffset = $this->Get_CurrentPage-1; 
				//prev link here
				$this->Gener_Html_Links=' <a class="'.$this->Def_Css_NumLinks.'"  href="'.$this->Def_WorkingScriptName.'?p=1'.$this->Get_Link_UrlExtraParameters.'">&lt;&lt;&lt;</a> | <a class="'.$this->Def_Css_NumLinks.'"  href="'.$this->scriptname.'?p='.$prevOffset.$this->Get_Link_UrlExtraParameters.'">'.$this->Def_Html_Link_PreviousText.'</a> |  '.$this->Gener_Html_Links; 
			}else {
				$this->Gener_Html_Links = '<span class="'.$this->Def_Css_NumLinks.'">'.$this->Def_Html_Link_PreviousText.'</span> | '.$this->Gener_Html_Links;
			} //endif
			//NEXT LINK
			//If the page not last page, set the nextOffset and show the link
			//If the page is the last page disable the link
			if ( !($this->Get_CurrentPage == $totalCalculatedPages) && $totalCalculatedPages!=1) { 
				$nextOffset = $this->Get_CurrentPage+1; 
				
				$this->Gener_Html_Links.=' <a class="'.$this->Def_Css_NumLinks.'"  href="'.$this->Def_WorkingScriptName.'?p='.$nextOffset.$this->Get_Link_UrlExtraParameters.'">'.$this->Def_Html_Link_NextText.'</a>';
				$this->Gener_Html_Links.=' | <a class="'.$this->Def_Css_NumLinks.'"  href="'.$this->Def_WorkingScriptName.'?p='.$totalCalculatedPages.$this->Get_Link_UrlExtraParameters.'">&gt;&gt;&gt;</a>'; 
			}else {
				$this->Gener_Html_Links.= ' <span class="'.$this->Def_Css_NumLinks.'">'.$this->Def_Html_Link_NextText.'</span>';
			}//endif

		}//endif(shownothing)

		//HTML OUTPUT
		if( $this->Get_SearchPhrase ){
			$intotalpagesText='" <i>'.$this->Get_SearchPhrase.'</i> " '.$this->Def_Html_InTotalPagesText;
		}else{
			$intotalpagesText=$this->Def_Html_TotalPagesFoundText;
		}
		$this->Gener_Html_TotalRecordsInfo = $intotalpagesText.':'.$totalCalculatedPages.'  ('.$this->Calculated_TotalRowsNum.' '.$this->Def_Html_RecordsText.'), '.$this->Def_Html_CurrentPageText.' '.$this->Get_CurrentPage;

		if(!isset($this->Def_Css_TotalRecordsandLinksTableTd) OR $this->Def_Css_TotalRecordsandLinksTableTd=='paginTd') {
			$css_pagin='<style type="text/css">
			<!--
			.paginTd {
				font-family: Arial, Helvetica, sans-serif;
				background-color: #FFFFFF;
			}
			.Pgn {
				font-family: Arial, Helvetica, sans-serif;
				font-size: 12px;
				font-weight: bold;
				color: #333333;
			}
			.Pgn:link {
				color: #003366;
			}
			.Pgn:hover {
				color: #FF0000;
				text-decoration: none;
			}
			.Pgn:visited {
				color: #003366;
			}
			-->
			</style>';
		}else{
			$css_pagin='';
		}

		$this->Gener_Html_TotalRecordsandLinks = $css_pagin.'
			<TABLE width="100%" border=0 cellspacing=1 cellpadding=2><TR>
				<TD class='.$this->Def_Css_TotalRecordsandLinksTableTd.'>'.$this->Gener_Html_Links.$this->Gener_Html_ReturnMessage.'</TD>
			</TR>
			<TR>
				<TD class='.$this->Def_Css_TotalRecordsandLinksTableTd.'>'.$this->Gener_Html_TotalRecordsInfo.'</TD>
			</TR></TABLE>';

		Return true;
	}

	//tool function
	function PaginationNumericLinks($lowlim,$toplim) {
		$returnval="";
		//Using a for() loop, Display links for each page. 1 2 3
		for ($i=$lowlim;$i<=$toplim;$i++) { 
			//If the page being viewed is the current page, disable the link
			if ( $this->Get_CurrentPage == $i ) { 
				$returnval.=' <span class="'.$this->Def_Css_NumLinks.'">'.$i.'</span> | ';
			}else {
				//If not current page, set nextOffset and display link
				$nextOffset= $i; 
				$returnval.='<a href="'.$this->Def_WorkingScriptName."?p=".$nextOffset.$this->Get_Link_UrlExtraParameters.'" class="'.$this->Def_Css_NumLinks.'">'.$i.'</a> | ';
			}//endif 			
		}
		Return $returnval;
	}

}; //end class


?>
Return current item: Pagination optimized