Location: PHPKode > scripts > PDO Paginator > PDOPaginator.php
<?php
/**
 * PDOPaginator: PHP Paginator for PDO
 * Copyright (C) 2010  Anderson Makiyama
 * 
 * PDOPaginator is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * PDOPaginator 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PDOPaginator; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    PDOPaginator 
 * @package     PDOPaginator
 * @author      Anderson Makiyama
 * @copyright   2010 Anderson Makiyama
 */


/**
 * PDOPaginator Main Class
 * 
 * @category    PDOPaginator 
 * @package     PDOPaginator
 * @author      Anderson Makiyama
 * @link        http://livrophp.com
 * @copyright   2010 Anderson Makiyama
 * @version     1.0
 */

class PDOPaginator extends PDO{
   public $sessionName;
   public $maxNavigationLinks = 20;                 //The number of links to show
   public $maxRegistriesPerPage = 10;               //The number of data base rows to show per page
   private $startPage = 0;
   private $query = null;
   private $allBindParams = null;
   private $sql=null;
   private $resultLength = null;
   function __construct($dsn, $user, $pass=null, $driver_options=null){
      parent::__construct($dsn,$user,$pass,$driver_options);
   }
   function prepareLimit($sql,$maxReg=10,$maxNav=20, $sessionName, $driver_options=array()){
      $this->sessionName = $sessionName;
      $this->maxNavigationLinks = $maxNav;
      $this->maxRegistriesPerPage = $maxReg;
      $this->allBindParams = null;
	  $this->startPage = 0;
      $this->sql = $sql;
      $sql = $sql . " LIMIT " . ":pg" . "," . $this->maxRegistriesPerPage;
      $this->query = parent::prepare($sql, $driver_options);
   }
   function bindParam($param1, $param2,$dataType){
	  if($param1==":pg"){
	     $this->startPage = $param2; $param2*=$this->maxRegistriesPerPage;
		 $this->query->bindParam($param1,$param2,$dataType);
	     return;
	  }
	  $this->query->bindParam($param1, $param2, $dataType);
	  $this->allBindParams[] = array($param1,$param2,$dataType); 
   }
   function execute(){
	  $this->query->execute();
	  return $this->query; 
   }
   function getQueryResultLength(){                  //Method to get Sql Result length widthout LIMIT parameter
      if($this->resultLength!=null) return $this->resultLength;
      $tempQuery = parent::prepare($this->sql);
      for($i=0;$i<count($this->allBindParams);$i++){
	     $tempQuery->bindParam($this->allBindParams[$i][0],$this->allBindParams[$i][1],$this->allBindParams[$i][2]);
	  }
	  $tempQuery->execute();
	  $this->resultLength = count($tempQuery->fetchAll(PDO::FETCH_COLUMN,0));
	  return $this->resultLength;
   }
   function getLinks($tipo, $target=""){  //first param is the type of links, set with ajax to ajax links. Second param is the target to open the page
      $_SESSION[$this->sessionName] = isset($_SESSION[$this->sessionName])?$_SESSION[$this->sessionName]:((int)($this->getQueryResultLength()/$this->maxRegistriesPerPage)+($this->getQueryResultLength()%$this->maxRegistriesPerPage==0?-1:0));
	  if($_SESSION[$this->sessionName]<0) return "A consulta não retornou nenhum registro! <br>(0/0 páginas)";
	  if (empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
	  $linksAround = (int)($this->maxNavigationLinks/2);
	  $firstLink = $this->startPage - $linksAround<0?0:$this->startPage - $linksAround;
	  $lastLink = $this->startPage + $linksAround>$_SESSION[$this->sessionName]?$_SESSION[$this->sessionName]:$this->startPage+$linksAround;
	  $lastLink = $firstLink == 0?($firstLink+$this->maxNavigationLinks>$_SESSION[$this->sessionName]?$_SESSION[$this->sessionName]:$firstLink+$this->maxNavigationLinks): $lastLink;
	  $firstLink = $lastLink==$_SESSION[$this->sessionName]?($lastLink-$this->maxNavigationLinks<0?0:$lastLink-$this->maxNavigationLinks):$firstLink;
	  $numeralLinks = "";
	  $fullParams = "";
	  for($i=0;$i<count($this->allBindParams);$i++){
	    if($this->allBindParams[$i][0]==":pg") continue;
	    $fullParams.= ",".str_replace(":","",$this->allBindParams[$i][0]) . ":'" .str_replace("%","",$this->allBindParams[$i][1]) . "'";
	  }
	  switch($tipo){
	  case "ajax":                                        //Case Ajax type, will return ajax links;
	     for($i=$firstLink;$i<=$lastLink;$i++){           //Create numeral Links
			 $tmp = $i; $tmp++;
			 if($this->startPage==$i){
				$numeralLinks.= $tmp . "&nbsp;";continue;
			 }
			 $numeralLinks.= "<a href='#' onclick=\"javascript:\$('". $target ."').html(loading);$.post('". $PHP_SELF ."',{p: '". $i . "'" . $fullParams . "},function (data, textStatus) { $('" . $target . "').html(data)});\">". $tmp . "</a>&nbsp;";
		  }                                              //Create << >> LINKS
		  $first = $this->startPage!=0?"<a href='#' onclick=\"javascript:\$('". $target ."').html(loading);$.post('". $PHP_SELF ."',{p: '0'". $fullParams ."},function (data, textStatus) { $('" . $target . "').html(data)});\">inicio </a>":"inicio ";  
		  $last = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='#' onclick=\"javascript:\$('". $target ."').html(loading);$.post('". $PHP_SELF ."',{p: '" . $_SESSION[$this->sessionName] . "'". $fullParams ."},function (data, textStatus) { $('" . $target . "').html(data)});\"> fim</a>":" fim";
		  $next = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='#' onclick=\"javascript:\$('". $target ."').html(loading);$.post('". $PHP_SELF ."',{p: '" . ($this->startPage + 1) . "'". $fullParams ."},function (data, textStatus) { $('" . $target . "').html(data)});\">>></a>":">>";
		  $back = $this->startPage!=0?"<a href='#' onclick=\"javascript:\$('". $target ."').html(loading);$.post('". $PHP_SELF ."',{p: '" . ($this->startPage - 1) . "'". $fullParams ."},function (data, textStatus) { $('" . $target . "').html(data)});\"><<</a>":"<<"; 
		  return "(". ($this->startPage + 1) ."/" . ($_SESSION[$this->sessionName] + 1) . " paginas) &nbsp;&nbsp;&nbsp;". $first ."&nbsp;". $back . "&nbsp;&nbsp;&nbsp;" . $numeralLinks . "&nbsp;&nbsp;&nbsp;" . $next . "&nbsp;" . $last;
	  break;
	  case "friendlyUrl":
	     $fullParams=str_replace(" ","", $fullParams);
	     $fullParams=str_replace("'", "", $fullParams);
		 $fullParamsArray = split(",",$fullParams);
		 $fullParams = "";
		 $totalParams = count($fullParamsArray);
		 for($i=0;$i<$totalParams;$i++){
		    $fullParams.= substr($fullParamsArray[$i], (strpos($fullParamsArray[$i],":")+1)) . "/";
		 }	  
	     for($i=$firstLink;$i<=$lastLink;$i++){           //Create numeral Links
		    $tmp = $i; $tmp++;
			if($this->startPage==$i){
				$numeralLinks.= $tmp . "&nbsp;";continue;
			}
			$numeralLinks.= "<a href='http://". $_SERVER['HTTP_HOST'] . $fullParams . $i .".html'>". $tmp . "</a>&nbsp;";
		 }  	 
		 $first = $this->startPage!=0?"<a href='http://". $_SERVER['HTTP_HOST'] .  $fullParams ."0.html'>first </a>":"first ";  
		 $last = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='http://". $_SERVER['HTTP_HOST'] . $fullParams . $_SESSION[$this->sessionName] .".html'> last</a>":" last";
		 $next = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='http://". $_SERVER['HTTP_HOST'] . $fullParams . ($this->startPage + 1) . ".html'>>></a>":">>";
		 $back = $this->startPage!=0?"<a href='http://". $_SERVER['HTTP_HOST'] . $fullParams . ($this->startPage - 1) . ".html'><<</a>":"<<"; 
		 return "(". ($this->startPage + 1) ."/" . ($_SESSION[$this->sessionName] + 1) . " pages) &nbsp;&nbsp;&nbsp;". $first ."&nbsp;". $back . "&nbsp;&nbsp;&nbsp;" . $numeralLinks . "&nbsp;&nbsp;&nbsp;" . $next . "&nbsp;" . $last;			 
	  break;
	  default:                                            //Will return default type of links with anchors
         $fullParams = str_replace(":", "=",$fullParams);
		 $fullParams = str_replace("'","",$fullParams);
		 $fullParams = str_replace(",","&",$fullParams);
		 for($i=$firstLink;$i<=$lastLink;$i++){           //Create numeral Links
		    $tmp = $i; $tmp++;
			if($this->startPage==$i){
				$numeralLinks.= $tmp . "&nbsp;";continue;
			}
			$numeralLinks.= "<a href='". $PHP_SELF . "?p=" . $i . $fullParams . "'>". $tmp . "</a>&nbsp;";
		 }                                              //Create << >> LINKS
		 $first = $this->startPage!=0?"<a href='". $PHP_SELF . "?p=0". $fullParams ."'>first </a>":"first ";  
		 $last = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='". $PHP_SELF . "?p=" . $_SESSION[$this->sessionName] . $fullParams . "'> last</a>":" last";
		 $next = $this->startPage!=$_SESSION[$this->sessionName]?"<a href='". $PHP_SELF . "?p=" . ($this->startPage + 1) . $fullParams . "'>>></a>":">>";
		 $back = $this->startPage!=0?"<a href='". $PHP_SELF . "?p=" . ($this->startPage - 1) .$fullParams . "'><<</a>":"<<"; 
		 return "(". ($this->startPage + 1) ."/" . ($_SESSION[$this->sessionName] + 1) . " pages) &nbsp;&nbsp;&nbsp;". $first ."&nbsp;". $back . "&nbsp;&nbsp;&nbsp;" . $numeralLinks . "&nbsp;&nbsp;&nbsp;" . $next . "&nbsp;" . $last;	 
	  }
   }   
}
?>
Return current item: PDO Paginator