2 Oct 2012

building simple php pagination script in 10 steps

Pagination is simply a process of dividing your output contents in small modules and displaying them on different pages.
For example,you can see Google search results where 10 to 15 search results are shown per page.
Pagination make output more user friendly.

Process for creating pagination script in 10 steps:

Today i'll develop pagination script in 10 easy steps.So let's get started, first of all Create two php files, 
  1.  pagination.php (for connection with Database and calculation) 
  2.  index.php        (for pagination display)
Note: I will be using 'pagination' as database name and 'data' as table name, change it according to your database and table name. 
Step 1: Open Pagination.php file in any of your favourite text editor and connect to database
<!-------------------------pagination.php --------->
<?php
 // connect to mysql//
//step:1

$con = mysql_connect("localhost","root",""); // Enter hostname,user,password 
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  // select database
  mysql_select_db("pagination", $con); //Provide database name which has our data for pagination.
  
Step 2: Count number of rows in table
//   count total number of rows from the desired table in the database  //
//step:2
    
  $query = mysql_query("SELECT * FROM data"); //Counting total number of rows in the table 'data',
  $total_rows = mysql_num_rows($query);
Step 3: Setup configuration
// setup configuration//  
//step:3

  $base_url = 'https://localhost/pagi/';    //Provide location of you index file  
  $per_page = 10;                           //number of results to shown per page 
  $num_links = 8;                           // how many links you want to show
  $total_rows = $total_rows; 
  $cur_page = 1;                           // set default current page to 1
Step 4: Extract information from url,when request made through pagination links
//now we will extract information from url//
//step:4
    if(isset($_GET['page']))
    {
      $cur_page = $_GET['page'];
      $cur_page = ($cur_page < 1)? 1 : $cur_page;            //if page no. in url is less then 1 or -ve
    }
Step 5: Calculate limit and offset for Querying Table
// calculate limit and offset, it'll will be used for Sql Query//
//step:5
    $offset = ($cur_page-1)*$per_page;                //setting offset
   
    $pages = ceil($total_rows/$per_page);              // no of page to be created
Step 6: Calculating the start and end page numbers for pagination links
//Calculate the start and end page numbers for pagination links//
//step:6

    $start = (($cur_page - $num_links) > 0) ? ($cur_page - ($num_links - 1)) : 1;
    $end   = (($cur_page + $num_links) < $pages) ? ($cur_page + $num_links) : $pages;
Step 7: Query the Database for displaying only 10 ['$per_page'] item per page.
//query the database with calculated OFFSET //
//step:7
    $res = mysql_query("SELECT * FROM data LIMIT ".$per_page." OFFSET ".$offset);

 mysql_close($con);
 
 // pagination.php completed // 
?>
Till now we have completed our work on pagination.php next we will work on index.php, As follows.
Step 8: Display the results in index.php
In this example table 'data' has id,title and content field , so I am going to display them as follows.
<!-- Now We are in index.php ---->
<!DOCTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="eng">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Pagination</title>

    </head>
    <body>    
    <?php
 
    include("pagination.php"); // DON'T FORGET THIS

     //        display the results //
     //step:8
     
        if(isset($res))// results from Step 7
        {
            //creating table
            echo '<table style="width:600px; cell-padding:4px; cell-spacing:0; margin:auto;">';           echo'<th>id</th><th>title</th><th>content</th></tr>'; 
            while($result = mysql_fetch_assoc($res))
            {
              echo '<tr>';
              echo '<td>'.$result['id'].'</td>'.'<td>'.$result['title'].'</td>'.'<td>'.$result['content'].'</td>' ;
              echo '</tr>';
            }
            echo '</table>';
        }
    ?>
Step 9: Display Pagination Page Numbers
<!--//display pagination page numbers //
    //step:9 
    -->
    <div id="pagination">
        <div id="pagiCount">
            <?php
                if(isset($pages))
                {  
                    if($pages > 1)        
                    {    if($cur_page > $num_links)     // for taking to page 1 //
                        {   $dir = "first";
                            echo '<span id="prev"> <a href="'.$_SERVER['PHP_SELF'].'?page='.(1).'">'.$dir.'</a> </span>';
                        }
                       if($cur_page > 1) 
                        {
                            $dir = "prev";
                            echo '<span id="prev"> <a href="'.$_SERVER['PHP_SELF'].'?page='.($cur_page-1).'">'.$dir.'</a> </span>';
                        }                 
                        
                        for($x=$start ; $x<=$end ;$x++)
                        {
                            
                            echo ($x == $cur_page) ? '<strong>'.$x.'</strong> ':'<a href="'.$_SERVER['PHP_SELF'].'?page='.$x.'">'.$x.'</a> ';
                        }
                        if($cur_page < $pages )
                        {   $dir = "next";
                            echo '<span id="next"> <a href="'.$_SERVER['PHP_SELF'].'?page='.($cur_page+1).'">'.$dir.'</a> </span>';
                        }
                        if($cur_page < ($pages-$num_links) )
                        {   $dir = "last";
                       
                            echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.$pages.'">'.$dir.'</a> '; 
                        }   
                    }
                }
            ?>
        </div>
    </div>
   
</body>
</html>
Step 10: Finally Add some css in the <head></head> section of index.php Change this CSS as it pleases you.
<!DOCTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="eng">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Pagination</title>
        
        <style type="text/css">
            /* Double Click to Copy and paste Style in <head></head> of index.php */ 
            #pagination {
                display: block;
                text-align: center;
            }
            #pagiCount{
                display: inline-block;
                margin: auto;
            }
            #pagiCount a, #pagiCount strong {
                display: block;
                width: 50px;
                background: rgb(0, 53, 148);
                float: left;
                margin-right: 5px;
                color: #fff;
                text-align: center;
                text-decoration: none;
                font-size:20px;
                line-height: 29px;
            }
            #pagination strong , #pagination a:hover {
                background:rgb(130, 171, 245);
                color:#000;
                font-size:22px;
            }
            tr:nth-child(even) {
                background: #CCC
            }
        </style>
And finally our pagination script is ready to use.
Download Pagination Database used in above code and import in your phpMyAdmin for experimenting purpose
Did you find this post useful? Let Us know in the comments section below.

9 comments:

  1. Thnx...... Sam se mera dimag kharap ho ja raha tha..........Thnx a lot

    ReplyDelete
  2. Thank U Very Much for Providing dis Code. It is Very Helpfull to Me as a Bigener in PHP

    ReplyDelete
  3. Thank you for your code..Its working..

    ReplyDelete
  4. how did you manage to get the Next/Previous links to work.

    ReplyDelete
  5. how did you manage to get the Next/Previous links to work.

    ReplyDelete
  6. how did you manage to get the Next/Previous links to work.

    ReplyDelete
    Replies
    1. Hi Patrick,
      For Next/Previous Links I am taking help of URL,
      For example,
      If current URL is 'http://localhost/pagi/' then GET['page'] returns 'FALSE',So no previous link only next ;
      If, current URL is 'http://localhost/pagi/index.php?page=n' then GET['page'] returns 'n',So set offset equal to (n-1)*10, set current page location to 'n' and set link for previous anchor as 'http://localhost/pagi/index.php?page=(n-1)' and link for next anchor is 'http://localhost/pagi/index.php?page=(n+1)'

      I hope that it helped you, for more clarity go through step 4 to step 9 again.
      Reply if it helped ?

      Delete