Simple pagination script in php

Here is a simple php code to show pagination in your website.We just have to include the class file and call the methods in the class to implement the pagination.Implementation is shown below.


First copy the code of the paginator class file shown below:

<?php
class paginator
{
 private $limit;
 private $num;
 private $query; 
 function __construct($str,$n)
 {
  $this->limit=$n;
  $this->query=$str;
  $this->num=mysql_num_rows(mysql_query($str));
  
 } 
 function paginate_query()
 {
  $n=$this->limit;
  if(!isset($_GET['a']) || $_GET['a']==0)
  {
   $a=0;
  }
  else 
  {
   $a=$_GET['a']; 
  }
  $str=$this->query." limit $a,$n";
  $result=mysql_query($str);
  return $result;
 }
 function paginate_show()
 { 
  $x=0;
  $p=1;
  $prev=0;
  if(isset($_GET['a']))
  {
   $next=$_GET['a'];
   $prev=$_GET['a'];
   $a=$_GET['a'];
  }
  else 
  {
      $next=0;
   $prev=0;
   $a=0; 
  }
  echo "<div id='paginate'>";
  $prev=$prev-$this->limit;
  echo "<b><a class='prev-next' href='?a=$x'>first</a></b>";
  if($prev>=0)
  {
   echo "<a href='?a=$prev' class='prev-next'>prev</a>";
  }
  while($x<$this->num)
  {
   $curr=$a/$this->limit;
   $curr=$curr+1;
   if($p==$curr)
   {  
     echo "<b><a class='pagenow' href='?a=$x'>$p</a></b>";
   }
   else 
   {
      echo "<a href='?a=$x'>$p</a>";
   }
      $p++;
   $x=$x+$this->limit;
   
  }
  $next=$next+$this->limit;
  if($next<$this->num)
  {
   echo "<a href='?a=$next' class='prev-next'>next</a>";
  }
  $x=$x-$this->limit;
  echo "<b><a class='prev-next' href='?a=$x'>last</a></b>"; 
  echo "</div>"; 
 }
}
?>

Save it as paginate.php.



Now here is the paginator style that needs to be included in your page

#paginate
{
 margin-top:30px;
 text-align:center;
}
#paginate a
{
 padding:5px;
 text-decoration:none;
 margin:5px;
}
.prev-next
{
 background-color:#387DEB;
 color:#fff;
 font-weight:bold;
}
.pagenow
{
   background-color:#000;
   color:#fff
}






Then here is the code to implement paginator.In the page where you wish to implement paginator do as follows:

<?php
include_once('paginate.php'); //include the class file

$page=new paginator("SELECT * FROM `article`",2); //create an object of the class with arguments,the query to be executed and the no of posts to be shown

$result=$page->paginate_query(); // use this function where you wish to show the contents,the function would return the result set,you can use the result set to display the contents

$page->paginate_show(); //write this code to show pagination

?>


Thats all :)


5 comments:

  1. It looks nice but for newby programmers the instructions are spartan and example would come in handy too so we could visualize it.

    ReplyDelete
    Replies
    1. Hi Stephen I have put a more easy to implement php pagination script.Hope it helps and thank you for providing your valuable feedback.Please ask if yo have any doubt in this post :)

      Delete