All pastes #199966 Raw Edit

Something

public php v1 · immutable
#199966 ·published 2006-10-12 21:16 UTC
rendered paste body
<?/////////////////////////// PAGINATION F U N C T I O N S ///// // VERSION 2.8.1// (major difference from what was used in the Real Estate Modules)//  - graham real estate, seaview properties//// this version implements the mod-rewrite compatible stuff I added to graham// and cleans up variable names and adds some more stuff// // Last updated June 30th 2006// see change log at bottom////////////////////*::::::::::::::::::: Usage Guide :::::::::::::::::::This class only works in conjunction with SESSIONS, so...session_start();But let me explain why I used sessions for this.If it's a really intricate search form that lets the usersearch on lots of criteria, I'm probably going to want to have thesearch form and search results page as 2 separate files.Since the sql is not calculated or hard coded in the results file there needs to be a way for that other file ands its paginated pages to know the sql they're searching with. I don't want all that info in the url on every page click.So, to keep the sql generated by the submitted form be the sql used by the paginatin class on all pages, I just save it temporarily in the session.Being on page 1 usually meas you just came there from submitting the form andat that point you'd want the sql calculated from the form to be stored inthe SESSION.Nothin but the phpsessionid is ever stored in user's cookie.First define the sql statement that will find all possible resultsThis sql will find the names of all countries	$sql = "SELECT * FROM tblcountry ORDER BY cTitle ASC";Create the new pagination object (I like to call it $pgn8)and feed it the sql and the number of results per page desired		$pgn8 = new pagination($sql, 20); // 20 items per page		Display the "Showing  1 - 5  of 28 Results Found" text.It does it by comparing the total found to the limit per page and which page you're currently on or something...		echo $pgn8->showingFromTo();Of course to keep the results per page limited you will need to query the DB on every page call to get a result resource to loop through.Use this per page result set to loop through and display your data.	$page_result = $pgn8->findPageResult();		while($info = mysql_fetch_assoc($page_result))		{ do stuff }And at the end of it all you can display your styled list of page numbers	echo $pgn8->displayPagination(); // show clickable page numbersYes, you can also use displayPagination() before you display your data loopto have it on the top as well as the bottom///// optional parameters ///////////////////////////////////////////////////Set the base url to be used on all the page number linksexample: page.php or the result of my thispage() functionor one of the $_SERVER['phpself thingies]		$pgn8->base_url=thispage();Do not use a query string when you set this value since theclass appends '?page=2' to the links for the pagination.If you have more arguements you need to pass via query stringuse the appendURLString() function to append to the ?page=2[&this=that&apple=red] etcYou can overwrite the whole url string using setUrlString or just append to it.	$pgn8->appendUrlString("&amp;island=eleuthera&amp;settlement=tbay");functions are camelCappedvariables are under_scored usually...:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/class pagination{	/////////////////////////////////////////////////	// PUBLIC VARIABLES	/////////////////////////////////////////////////		var $base_url;		var $limit_per_page;		var $url_string;				// the display of 'showing from to' and the page numbers		// can be turned off by setting these to FALSE				var $display_showing_from	=	TRUE;		var $display_pagination		=	TRUE;		var $display_label			=	TRUE;		var $display_first_last 	=	TRUE;				var $modRewrite = FALSE; // controls how the page number will be appended to the url				/**		* If you need separate areas of a site to use pagination 		* but don't want their sql clashing when going from section to section,		* use a different session variable name on each page 		* for the stored sql used by the class		* @var string		*/		var $session_var = 'pgn8_search_sql';		var $sql;				// sql string that will find all of whats requested			/////////////////////////////////////////////////	// VARIABLES CALCULATED INTERNALLY	/////////////////////////////////////////////////		var $total_found;		// total number of items found with $sql		var $pages;				// total number of pages needed based on calculating limit per page and amount found		var $current_page;			var $offset;		var $limitstring;			/////////////////////////////////////////////////	// VARIABLE METHODS	/////////////////////////////////////////////////		function setBaseUrl($url)		{			$this -> base_url = $url;		}				function setUrlString($value) // overwrites url_string		{			$this -> url_string = $value;		}				function appendUrlString($value) // attaches to the end of url_string		{			$this -> url_string .= $value;		}			/////////////////////////////////////////////////	// RUNS ON CREATION	/////////////////////////////////////////////////	/**	* :: INITIALIZING METHOD ::	* this function will auto run 	* upon the creation of a new pagination object	* @param string $sql	* @param int $sql	* @return void	*/	function pagination($sql, $perpage=10, $session_varname='pgn8_sql')	{		$this->sql = $sql;		$this->limit_per_page = $perpage;		$this->session_var =  $session_varname;		$this->determinePage();		$this->calcOffset();		$this->setBaseUrl(basename($_SERVER['PHP_SELF']));		$this->findTotalResult();		$this->calcPages();			}	/////////////////////////////////////////////////////////	// INTERNAL CALCULATION METHODS		/////////////////////////////////////////////////////////		function findTotalResult()		{			$total_result = mysql_query($this->sql) or die('pgn8-findTotalResult-'.mysql_error());			$total = mysql_num_rows($total_result);			$this->setTotalFound($total);			return $total;		}			function setTotalFound($value)		{	// if the total found is 0, disable the showing of 'pagination' and 'showing from to'			if($value<=0)			{				$this -> display_showing_from = FALSE;				$this -> display_pagination = FALSE;			}			else { $this->total_found = $value;}		}				function calcOffset()		{	// calcOffset calculates the difference needed to select 			// just the range of results needed for one page			// the vars needed for the calculation are the same ones used in the limitstring			// so fill in the limitstring var at the same time which is appened to the sql var						$this->offset = ($this->current_page*$this->limit_per_page) - $this->limit_per_page;			$this->limitstring=" LIMIT {$this->offset}, {$this->limit_per_page}";		}				function findPageResult()		{			$page_result = mysql_query($this->sql.$this->limitstring) 			or die('pgn8-findPageResult-'.mysql_error());			return $page_result;		}				/////////////////////////////////////////////////////////		// 	NON - SQL STUFF BELOW			/////////////////////////////////////////////////////////		function determinePage()		{			if(isset($_GET['page']) and $_GET['page'] != 0) 			{				$this->setCurrentPage($_GET['page']);								// if i'm coming through a pagination link just use the stored sql 				// in the $_SESSION IF IT EXISTS				// instead of rebuilding it.		}				if(!empty($_SESSION[$this->session_var])) 				{					$this->sql = $_SESSION[$this->session_var]; 				}			}			else 			{				$this->setCurrentPage(1);				$_SESSION[$this->session_var] = $this->sql; 			}					}				function setCurrentPage($value)		{			$this->current_page = (!is_numeric($value) || $value > $this->pages || $value < 1) ? intval($value) : 1 ; 		}				function calcPages()		{			// how many pages needed to display all the found results			$this->pages = ceil($this->total_found / $this->limit_per_page);												// based on the current page, what would be 5 pages before and 5 pages after			if($this->current_page > 6)			{				$this->rangeStart = $this->current_page - 4;			} else {$this->rangeStart = 1;}						if($this->current_page <= 6)			{				$this->rangeEnd = $this->current_page + (10 - $this->current_page);			} else 					{						$this->rangeEnd = $this->current_page+5;						if($this->rangeEnd > $this->pages) { $this->rangeEnd = $this->pages; }									}								if($this->current_page > $this->pages - 6) {				$this->rangeStart = $this->pages - 9;			}			if($this->rangeStart < 1){ $this->rangeStart = 1;}			if($this->rangeEnd >= $this->pages) { $this->rangeEnd = $this->pages; }			}			/////////////////////////////////////////////////	// OUTPUT METHODS	/////////////////////////////////////////////////		function showingFromTo()		{			$this->calcOffset(); // just in case it wasn't already calculated						$start = $this->offset + 1;			$finish = $this->offset + $this->limit_per_page;			if ($finish >= $this->total_found) {			$finish = $this->total_found; }			$to_echo = "<div id=\"pgn8_start_finish\">			Showing <b> $start - $finish </b> 			of <b>{$this->total_found}</b> Results Found</div>";			if($this->display_showing_from === TRUE)			{return $to_echo;}			else {return '';}		}		function displayPagination()		{			$to_echo = '';			$to_echo .= '<div class="pagination xxclearfix">' . "\n";			$to_echo .= '<ul>';						if($this->display_label === TRUE) {				$to_echo .= '<li class="pgn8Label">Page '.$this->current_page.' of '.$this->pages.'</li>';			}						if($this->display_first_last === TRUE) {				if($this->current_page >=6 and $this->rangeStart > 1)				{					$to_echo .= '<li class="first"><a href="'.$this->base_url;						if($this->modRewrite === FALSE){$pager = '?page=1';} else {$pager = '/1';}					$to_echo .= $pager.'">&laquo; First</a></li>';				}			}						for ($i = $this->rangeStart; $i <= $this->rangeEnd; $i++)			{					$to_echo .= '<li>';					//--//										if($i != $this->current_page)					{ // if we're not on the current page then make a numbered link						if($this->modRewrite === FALSE)						{	// if mod rewrite is not required for the links then use the normal ?page=number							$to_echo .= '<a href="' . $this->base_url . '?' . $this->url_string.'page='.$i.'">' . $i . '</a>' ;						}						else	{									// if modRewrite is TRUE then just append the page number with a slash - search/results/4									$to_echo .= '<a href="' . $this->base_url . '/' . $this->url_string . $i .'/">' . $i . '</a>' ;								}					}					else 	{						$to_echo .= '<span class="active">' . $i . '</span>';						}															/*					$to_echo .= ($i != $this->current_page) ? '<a href="' 								. $this->base_url . '?page=' . $i . $this->url_string.'">' . $i . '</a>' 									: '<span class="active">' . $i . '</span>';					*/					//--//					$to_echo .= ($i + 1 > $this->pages) ? '' : '  ';					$to_echo .= '</li>';			}						if($this->display_first_last === TRUE) {				if($this->current_page <= $this->pages-5 and $this->pages > $this->rangeEnd) 				{					$to_echo .= '<li class="last"><a href="'.$this->base_url;					if($this->modRewrite === FALSE){$pager = '?page='.$this->pages;} else {$pager = '/'.$this->pages;}					$to_echo .= $pager.'">Last &raquo;</a></li>';				}			}						$to_echo .= "</ul> \n" . '</div>' . "\n";						if($this->display_pagination === TRUE)			{return $to_echo;}			else {return '';}		 }        } //// end class  //// ////////////////////        /* ////// N O T E S /////////IMPORTANT NOTES FOR USING WITH MOD-REWRITE* 	your html pages MUST have a <base> tag in the header	<base href="http://gre.thymeonline.com/" />	or else the base_url appended to all the links will just grow 	longer and longer with each pageFor css styling purposes a class of 'clearfix' is on the wrapping div and ul..clearfix fixes the clearing floats problem using the method documented on positioniseverything.net:::Sample CSS Styling for display_pagination():::<style type="text/css" title="text/css">.pagination {margin:10px 0;height:26px;width:550px}.pagination ul {margin:0; padding:0}.pagination a {text-decoration:none;}.pagination .pgn8Label {display:block;width:auto;}.pagination .first, .pagination .last {width:50px;}.pagination span {display:block; float:left;}span.pages {height:34px;}.pagination ul {list-style-type:none;margin:0;padding:0;}.pagination ul li {float:left;width:25px;height:20px;line-height:22px;border:1px solid #ded;text-align:center;margin:2px 2px;overflow:hidden;}span.active {display:block;width:25px;text-align:center;background:#ded;}.pagination a {display:block;}.pagination a:hover {background:#ded;text-decoration:none;</style>/*/* Change Log ---------------June 30th* changed clearfix class because on some layouts having a clearfixed element in	the content area could cause all the content to be forced below the left or	right navigation.	Besides, i added clearfix to the back when it was just displaying a page 	number for every page found (up in the hundreds on some search) and I needed	the container to expand with the floated page numbers within it.	But now that it only shows 10 pages at a time, needing only one line, the clearfix	is not really needed :)June 19th, 2006* accidentally used $pgn8-> instead of $this-> in the determinePage function  that caused problems.* had to add the ability to change the name of the session_var in the default  class so it happens upon the creation of the objectJune 16th, 2006* Straightened out the naming conventions of the variables and functions.* Added mod-rewrite compatability* Added ability to change the name of the session variable containing the sql  using setSessionVar()June 6th, 2006* Continuing the major overhaul. Just trying to make it a bit 'smarter' overall.* Fixed the problem with the negative page ranges and   incorrect appearance/disappearance of the first and last links* Updated the example css* Also renamed some of the toggle vars to be display_etc...* Could use a bit more documentation in the user guide area for the optional vars* Copied to the common site folderMay 31, 2006Updated lots and lots of stuffmoved most of the stuff into the actual classand made it all more automatedTo invoke the pagination stuff in the page takes a lot less lines of code now.Feb 3, 2006Copied to default site folder/scriptsJan 04, 2006:converted to object oriented classOct 21, 2005:use of $this-> not allowed in PHP5+ because $this is a special reserved wordfor object oriented programming similar to 'this' in javascriptAug 15, 2005:fixed display_pagination_range function to show from offset to final total instead of from offset to +limit on the final pageof search results.ie. from 41-47 when only 47 total instead of 41-50 with only 47 total*/        ?>