Location: PHPKode > scripts > TPaginatedData > tpaginateddata/TPaginatedData.class.php
<?
/**
	TPaginatedData.class.php
	
	Implementation of TPaginatedData class for retriving and outputting data from a MySQL database in a paginated fashion.
	
	Created at 2006-05-03
	
	Copyright (c) 2006 Augustin Boteanu
	
	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/


/**
	Offers the possibility to retrive data from the database and output it in a paginated way,
	offering links to jump to any of the pages.
*/
class TPaginatedData {

	/**
		The SQL query to execute on database for retreiving the data.
		
		@access public
		@type string
	*/
	var $query;
	
	/**
		Number of items to be displayed on page
		
		@access public
		@type int
	*/
	var $itemsPerPage;
	
	/**
		Number of page links displayed
		
		@access public
		@type int
	*/
	var $visiblePages;
	
	/**
		Result set containing the data.
		
		@access public
		@type Resource
	*/
	var $rs;
	
	/**
		Total number of items in the database for the given query
		
		@access private
		@type int
	*/
	var $totalItemCount;
	
	/**
		Number of the current page (page displayed)
		
		@access public
		@type int
	*/
	var $currentPage;

	/**
		Total number of pages
		
		@access private
		@type int
	*/
	var $numPages;
	
	/**
		Contains the error message in case an error occured.
		
		@access public
		@type string
	*/
	var $error;


	/**
		Constructor of the class. Calculates the total number of items and total number of pages.
		
		@param $q string containing the query to be executed on database (from it the query to get the total number of items is generated automatically)
		@param $items integer representing number of items to be shown in each page
		@param $pages integer representing number of page links to show
		
		@return true if the total number of items was retrived from database, false otherwise.
	*/
	function TPaginatedData($q, $items=10, $pages=10) {
		$this->error = false;
		
		// extracting the part of the query before the column list:
		if( strpos($q, 'SELECT ALL') !== false ) {
			$qStart = 'SELECT ALL ';
		} elseif( strpos($q, 'SELECT DISTINCT') !== false ) {
			$qStart = 'SELECT DISTINCT ';
		} elseif( strpos($q, 'SELECT ') !== false ) {
			$qStart = 'SELECT ';
		} else {
			$this->error = "Incorrect or unsupported SQL query ( $q ).";
			return false;
		}
		
		// extracting the part of the query after the column list:
		$qEnd = substr( $q, strpos($q, "FROM") );
		
		// creating the query that counts the total number of items in the database:
		$countQuery = $qStart." count(*) item_count ".$qEnd;
		
		// retriving the total number of items:
		$rs = mysql_query($countQuery);
		
		if( !$rs ) {
			$this->error = "Error executing the count items query ( $countQuery ).\n MySQL Error: ".mysql_error();
			return false;
		}
		$this->query = $q;
		$this->itemsPerPage = $items;
		$this->visiblePages = $pages-1;
		$this->totalItemCount = mysql_result($rs, 0);
		$this->numPages = ceil($this->totalItemCount/$this->itemsPerPage);
		$this->curPage = 1;
		$this->rs = NULL;
		
		return true;
	} //~ TPaginatedData


	/**
		Gets from the database all items for page number $page.
		
		@param $page integer representing the page number to fetch products for.
		@return true on success, false on error
	*/
	function fetchPage($page) {
		$this->currentPage = $page-1;
		$rs = mysql_query( $this->query.' LIMIT '.($this->currentPage*$this->itemsPerPage).', '.$this->itemsPerPage );
		if( $rs ) {
			$this->rs = &$rs;
			return true;
		}
		$this->error = "Could not fetch the data for page ".($page-1)." from the database.\n MySQL Error: ".mysql_error();
		return false;
	}


	/**
		Outputs the links of the pages.
		
		@param $page	string containing the page and query string where the link points to. 
									If $url_rewrite is true $page content should be something like "./value1/value2/" 
									witch will output as "./value1/value2/3/" (where 3 is the page number). Note the trailing slash.
									IF $url_rewrite is false $page content schold be something like "mypage.php?var1=val1&amp;var2=val2&amp;" 
									witch will output as "mypage.php?var1=val1&amp;var2=val2&amp;page=3". Note the heading &amp; (&)
		@param $curPage integer representing the current page number
		@param $url_rewrite true if to format links with slashes (/), false if to format with ampersand (&)
	*/
	function pageLinks($page, $curPage, $url_rewrite=true) {	
		
		if( $this->numPages == 0 ) return;
		
		if( !$url_rewrite ) $cpage = 'page_no=1';
		else $cpage = '1/';
		echo '<div class="pagination_block"><a href="'.$page.$cpage.'" title="First page" class="first">&laquo;</a>';

		// testing if total pages number is higher than number of pages that must be visible
		if( $this->numPages <= $this->visiblePages ) {
			$nav_page_start = 1;
			$nav_page_stop 	= $this->numPages;
		} else { // testing if the current page is in the right interval. if it isn't we make the corrections.
			$nav_page_start = $curPage - floor($this->visiblePages / 2); 
			$nav_page_stop 	= $curPage + floor($this->visiblePages / 2);
			
			if($nav_page_start < 1) {
				$nav_page_stop = $curPage + abs($nav_page_start) + floor($this->visiblePages / 2);
				$nav_page_start = 1;
			} else if($nav_page_stop > $this->numPages) {
				$nav_page_start = $curPage - ($nav_page_stop - $this->numPages ) - floor($this->visiblePages / 2);
				$nav_page_stop =  $this->numPages;
			}
		}
		
		for($i=$nav_page_start; $i <= $nav_page_stop; $i++){
			if( !$url_rewrite ) $cpage = 'page_no='.$i;
			else $cpage = $i.'/';
			if($i==$curPage) echo '<span class="current">'.$i.'</span>';
			else echo '<a href="'.$page.$cpage.'" title="Page '.$i.'">'.$i.'</a>';
		}
		
		if( !$url_rewrite ) $cpage = 'page_no='.$this->numPages;
		else $cpage = $this->numPages.'/';
		echo '<a href="'.$page.$cpage.'" title="Last page" class="last">&raquo;</a></div>';
	} //~ pageLinks


	/**
		Uses the file specified by $template path to output the data.
		Inside the file all variables of this object can be retrived using $this->variableName (i.e. for the result set use $this->rs)
		
		@param $template string specifying the path to the file to be used as a template.
	*/
	function output($template) {
		include $template;
	}
	
} //~ class

?>
Return current item: TPaginatedData