1 Oct 2008

Function to generate a pagination link list in PHP

Filed under: Tutorials and HOWTOs by Hari
Posted at 12:04:16 IST (last updated: 3 Nov 2008 @ 16:10:50 IST)
When I was writing my blog software code, I came across a challenge peculiar to website scripts which require to display several pages of data. While actually retrieving the data for a particular page is simple enough using SQL queries (using SQL SELECT's LIMIT and OFFSET mechanism) generating a list of navigable links for each page of data is another cup of tea.

Let's assume that you want to generate a list of pages in PHP. E.g. You need to create a blog navigation toolbar, with links to each page on the footer.

The assumption is that you have hundreds of pages to display and you cannot display each page in the navigation toolbar, because that would become unwieldy. What you want is actually a list looking like this below (bolded item is current page):
Page: 1 2 3 4 5 ... 100

Or if the page is in the middle of the the navigation
1 ... 70 71 72 73 74 75 76 78 79 ... 100

If the page is at the end of this list
1 ... 92 93 94 95 96 97 98 99 100

This navigation scheme is not perfect, but it is adequate for most purposes. The following PHP function creates an array of navigable links which can be easily used to create such a pagination. This can be used as a generic pagination function, because it accepts all necessary parameters (including the base URL as well as the query string to use), total number of pages, current page and pagination limit. The pagination limits how many pages are actually shown around the current page.

<?php // Function to generate pagination array - that is a list of links
// for pages navigation
function paginate ($base_url, $query_str, $total_pages, 
                    $current_page, $paginate_limit)
{
    // Array to store page link list
    $page_array = array ();
    // Show dots flag - where to show dots?
    $dotshow = true;
    // walk through the list of pages
    for ( $i = 1; $i <= $total_pages; $i ++ )
    {
       // If first or last page or the page number falls 
       // within the pagination limit
       // generate the links for these pages
       if ($i == 1 || $i == $total_pages || 
             ($i >= $current_page - $paginate_limit && 
             $i <= $current_page + $paginate_limit) )
       {
          // reset the show dots flag
          $dotshow = true;
          // If it's the current page, leave out the link
          // otherwise set a URL field also
          if ($i != $current_page)
              $page_array[$i]['url'] = $base_url . "?" . $query_str .
                                         "=" . $i;
          $page_array[$i]['text'] = strval ($i);
       }
       // If ellipses dots are to be displayed
       // (page navigation skipped)
       else if ($dotshow == true)
       {
           // set it to false, so that more than one 
           // set of ellipses is not displayed
           $dotshow = false;
           $page_array[$i]['text'] = "...";
       }
    }
    // return the navigation array
    return $page_array;
} ?>

To use the function in a PHP page, you just have to simply walk through the array:
<?php // To use the pagination function in a 
// PHP script to display the list of links
// paginate 100 pages - current page is 50 and show
// 5 links around the current page
$pages = paginate ("myurl.php", "page", 100, 50, 5); ?>

<p>Pages: 
<?php 
// list display
foreach ($pages as $page) {
    // If page has a link
    if (isset ($page['url'])) { ?>
        <a href="<?php echo $page['url']?>">
		<?php echo $page['text'] ?>
	</a>
<?php }
    // no link - just display the text
     else 
        echo $page['text'];
} ?>
</p>

The output of the above code will be

Pages: 1 ... 45 46 47 48 49 50 51 52 53 54 55 ... 100

That's all. Hope you find it useful in your own PHP coding project. :)

6 comment(s)

Leave a comment »
  1. very good concept.. this is what i am seraching for a long time .. thanks a lot hari..

    Comment by jegan (visitor) on 2 Oct 2008 @ 17:32:25 IST #
  2. You're welcome, jegan. Glad to be of help. :D

    Comment by hari (blog owner) on 2 Oct 2008 @ 17:51:01 IST #
  3. I understood it, though I only skimmed it. I hate messing with code I'm unfamiliar with. Hopefully, I won't ever need to write any kind of paginating routines.

    Comment by RT Cunningham (visitor) on 2 Oct 2008 @ 18:07:48 IST #
  4. RT, if you're writing your own CMS or blog software, you'll need something like this - or at least a mechanism to navigate pages without too much clicking around.

    The logic is actually quite easy in the above code.

    Simply walk through the numbers 1 to max_page, displaying only the first and last pages and a preset number of pages before and after the current page.

    Comment by hari (blog owner) on 2 Oct 2008 @ 18:15:01 IST #
  5. I'm not sure where to place your code. I am new to PHP. My code:

    <?php

    $page=$_GET["page"]; //Get the page number to show
    If($page == "";) $page=1;

    $limit = "10"; //total comments per page

    $total_comments = mysql_query("SELECT * FROM ". COMMENTS ."";);
    $total =mysql_num_rows($total_comments);

    $total_pages=ceil($total_comments/$Limit);
    $offset = ($page - 1) * $Limit;

    for ($i=0; $i<=$total_pages; $i++) {
    $start = $limit * $i;

    $comments = mysql_query("SELECT * FROM ". COMMENTS ." LIMIT $start, $limit";);

    echo '<div class="virtualpage">';

    while ($row = mysql_fetch_array($comments)) {


    $test = $row['name'];
    ?>

    <div><?php echo $test;?></div>

    <?php
    }
    echo '</div>';

    }
    ?>

    </div>

    Can you please give me an idea? Would your code work in a tabbed content without reverting to the first tab?

    Comment by Margaret (visitor) on 22 Oct 2009 @ 22:12:57 IST #
  6. Hi, Margaret. I'm not sure what your question is. The PHP code is purely to generate the simple HTML code required to display the links for pages in a website or blog (a.k.a. pagination).

    How you actually interpret the page numbers in links (the query string), retrieve that data in the particular page and display the page is another story which is not in the scope of this article. It can be almost anything, depending on the type of data - including SQL queries for databases.

    The code does not address anything else at all, actually...

    Comment by Hari (blog owner) on 24 Oct 2009 @ 15:55:16 IST #

Leave a comment

First-time comments on this blog are moderated.
Your name*
Email ID*
(wont' be published)
Website
Your comments*
(No HTML allowed)
:-) :-D :biggrin: :-P ;-) 8-) :-( :mad: |-| :oops: :-/ :-| :roll:
bold italic quote code
Code* captcha Enter the code you see in the image
* required fields