How To Create Simple Cool Paging With PHP and CSS


It is quite common when you need of paging in your web application. A dynamic web is what consists of scripts and renders various pages depends upon the user requirements and where he/she wants to browse the web. Paging, categories, tags are all these type of browsing. We will talk about paging in this article and how to make it with simplest code in PHP. So let’s start:

Update:
We have a new article on How to implement paging with PHP / MySQL which will help you in coding where you want to implement the paging with mysql’s table data

paging screen shot
Paging screen shot: Live example is given below

Step 1: Define CSS styling

Create styling for paging numbers and links. See the code below, don’t worry will show you below how we will use it in this example. Inspired from Flickr and digg.

.paging { padding:10px 0px 0px 0px; text-align:center; font-size:13px;}
.paging.display{text-align:right;}
.paging a, .paging span {padding:2px 8px 2px 8px;}
.paging span {font-weight:bold; color:#000; font-size:13px; }
.paging a {color:#000; text-decoration:none; border:1px solid #dddddd;}
.paging a:hover { text-decoration:none; background-color:#6C6C6C; color:#fff; border-color:#000;}
.paging span.prn { font-size:13px; font-weight:normal; color:#aaa; }
.paging a.prn { border:2px solid #dddddd;}
.paging a.prn:hover { border-color:#000;}
.paging p#total_count{color:#aaa; font-size:12px; padding-top:8px; padding-left:18px;}
.paging p#total_display{color:#aaa; font-size:12px; padding-top:10px;}

Step 2: Create PHP function

The function below will take care of all your paging needs. Will show you how to use it in next step.

function doPages($page_size, $thepage, $query_string, $total=0) {
    //per page count
    $index_limit = 10;

    //set the query string to blank, then later attach it with $query_string
    $query='';

    if(strlen($query_string)>0){
        $query = "&".$query_string;
    }

    //get the current page number example: 3, 4 etc: see above method description
    $current = get_current_page();

    $total_pages=ceil($total/$page_size);
    $start=max($current-intval($index_limit/2), 1);
    $end=$start+$index_limit-1;

    echo '
'; if($current==1) { echo '< Previous '; } else { $i = $current-1; echo '< Previous '; echo '... '; } if($start > 1) { $i = 1; echo ''.$i.' '; } for ($i = $start; $i <= $end && $i <= $total_pages; $i++){ if($i==$current) { echo ''.$i.' '; } else { echo ''.$i.' '; } } if($total_pages > $end){ $i = $total_pages; echo ''.$i.' '; } if($current < $total_pages) { $i = $current+1; echo '... '; echo 'Next > '; } else { echo 'Next > '; } //if nothing passed to method or zero, then dont print result, else print the total count below: if ($total != 0){ //prints the total result count just below the paging echo ' (total '.$total.' results)
'; } }//end of method doPages() //Both of the functions below required function check_integer($which) { if(isset($_REQUEST[$which])){ if (intval($_REQUEST[$which])>0) { //check the paging variable was set or not, //if yes then return its number: //for example: ?page=5, then it will return 5 (integer) return intval($_REQUEST[$which]); } else { return false; } } return false; }//end of check_integer() function get_current_page() { if(($var=check_integer('page'))) { //return value of 'page', in support to above method return $var; } else { //return 1, if it wasnt set before, page=1 return 1; } }//end of method get_current_page()

Step 3: Usage

Call the doPages() function with proper parameters and you’re done!. See the code below:

//print the paging result
doPages(10, '/paging.php', 'category=sports', 123);
  1. First param is ’10′: It means we are displaying 10 results per page.
  2. Second param is ‘/paging.php’: It is the page link where we need to link the paging. It can be absolute or relative path.
  3. Third param is ‘category=sports’: It is extra query strings that we can pass to function to take care of existing query strings.
  4. Fourth param is 123: It is the actual result that is the basis of paging.

For example if we host a page like http://www.mywebsite.com/browse/page.php?category=sports and we want to add paging in it, then we need to call this function like this:
doPages(10, ‘/browse/page.php’, ‘category=sports’, 123);

If we are browsing page 5 then it will make page links like: http://www.mywebsite.com/browse/page.php?page=5&category=sports

A fully functional live example is given below. If you still face any difficulty in using this example. Please feel free to leave your comments.

About SachinKRaj

Sachin is a web application developer, technology blogger and web addict! He has over 6 years of web development experience and he writes tutorials primarily focused on LAMP, Ajax, Api's, jQuery etc. He is usability expert and he always likes to share his knowledge with people.

, , ,

61 Responses to How To Create Simple Cool Paging With PHP and CSS

  1. Sushil Kumar Raghav July 29, 2009 at 2:40 pm #

    This is such a nice example of paging which is created by this Guru of php called Sachin….. or Sach…. I thinks this example is very simple to uderstand and easy to implement so guys enjoy… and say thanks to Guru of php (Sachin).. and even you can post ur comments if you like this code…. :)

    Keep it up Sachin i know your blog will help us in learning php… or copying code… ha ha ha…lol…..

    Raghav…

  2. shubhamoy July 29, 2009 at 10:59 pm #

    Really amazing tutorial ;)
    If you proceed in this way then this blog will grow to new heights ;)

  3. ceema July 31, 2009 at 9:22 am #

    well done guys , keep it up

  4. ceema July 31, 2009 at 9:26 am #

    like u personality iz very essential in our world . well done sachin , be more better than now in future

  5. Gayash August 3, 2009 at 10:20 pm #

    its really appreciating.
    n paging gallery is really superb
    keep it up

  6. Emese August 21, 2009 at 10:19 pm #

    Your code is really helpful and great.
    Can you please let me know the way how to modify the code if I want to display .jpg images on the pages?
    I am plannig to have 4 times 3 images per page.
    Thank you for your help in advance.

  7. key August 22, 2009 at 11:31 pm #

    so, how to display my data from mysql?

  8. Amalan September 22, 2009 at 10:52 am #

    I’m using twitters account for searching.. I’m getting only 15 results.. I don’t know how to get all the results.. can u help me?

    thank you…

  9. Mitx November 8, 2009 at 10:42 pm #

    to Amalan, you can do this for example:

    $yourquery=”SELECT id FROM books”;
    $yourresult = mysql_query($yourquery) or die(“Error getting data.”);
    $totalresult=mysql_num_rows($yourresult);

    Then you call function like:

    doPages(12, ‘yourpage.php’, ”, $totalresult);

  10. Kunal November 9, 2009 at 12:06 am #

    Hi Mitx,

    I just applied your script and it works fine for me.
    Paging is displayed & working fine but the records per page are not coming as they are reqd. to be.

    I am writing this:

    doPages(6, ‘product_catalogue.php’, ‘CatId=’.$intCategoryID.’&SubCatId=’.$intSubCategoryID, $numrows);

    As per this it should show 6 results but its showing all the records that are coming in dataset.

    Please suggest.

  11. prashanth November 18, 2009 at 2:52 pm #

    please give a easiest code for paging in php.

  12. abhay December 22, 2009 at 10:57 am #

    Hey,
    i need this paging to work with my sql database…
    im trying to connect it with the mysql db but is shows the total number of records but its not displaying the records………..

  13. zeek333 February 2, 2010 at 8:56 pm #

    I try to add my sql to this as well
    I think there should be something $yourquery=”SELECT id FROM books LIMIT something “;

  14. Jacop April 13, 2010 at 5:17 am #

    its realy great tutorial, thanks

  15. lufti April 22, 2010 at 3:51 am #

    nice tuts how to add mysql query with your method…?

  16. rams June 15, 2010 at 9:56 pm #

    hi, i used this it's very nice and easy to use…………..
    but i want use for search results with paging get some problem could u explain how to use for this for search results for paging plz…..

    any how it's awesome dude……..

  17. Ankit June 27, 2010 at 1:52 am #

    Hi Sachin,i was trying this code but unable to do that…
    I have a page on which values are coming from DB. so how can i manuplate the things..can u give a example?
    suppose i have a admin.php on which 25 records are there which are coming from DB.how can i show the data in paging….
    Thanks in Advance

  18. @kaustubhkushte August 7, 2010 at 3:21 pm #

    Nice tutorial :) I used in one of my project :)

  19. Ndi Rustandi August 30, 2010 at 4:50 am #

    the data record from DB unable to show? hey buddy how to show do this for?
    example :
    while($data_cat = mysql_fetch_array($query_string))
    {
    echo htmlentities($data_cat['8']);
    }

    where i am putting this line code to show the record to integrate with your method paging?

    thnx=/

  20. pavinz September 3, 2010 at 7:36 pm #

    Hi There, i am totally new to the world of PHP, can anyone help me.
    the paging doesnt work for me, i dont have any categories at all to be included in the code,
    this is what i add in
    doPages(2, 'paging.php', '', 123);

    anyone help me, thanks a lot
    email me pavinz@yahoo.com

  21. kamlesh October 29, 2010 at 3:57 pm #

    Thank you Thank you very much dear……….
    I am so happy…..
    Dilse
    Kamlesh

    • SachinKRaj May 26, 2011 at 10:31 am #

      Thanks a lot for appreciating :)

  22. Andre November 26, 2010 at 4:28 am #

    This saves me a lot of time
    Thanks for sharing this.

  23. itman December 3, 2010 at 7:10 am #

    Great!!!!

  24. daBruce February 25, 2011 at 1:11 am #

    This is awesome – I'm working on a project with an insane deadline and spent a valuable day trying to do something like this with poor results. Then I found your page and had it up an running in 5 mins!

    You rock for posting this!! Thanks man!

    • SachinKRaj February 25, 2011 at 11:58 am #

      daBruce:

      Thanks a lot dear :)

  25. Nikolius February 26, 2011 at 11:30 am #

    thanks bro. really saves my time with your script. :)

    • SachinKRaj May 26, 2011 at 10:30 am #

      Thanks. :)

  26. dawe April 14, 2011 at 7:38 am #

    Nice… Thanks!

  27. Norman May 25, 2011 at 3:55 am #

    Hi Sachin, i'am a novice in php, i have been able to understand and implement your (doPages Function) so as paging appears in the website i'am developing, in (link1). I have created page2.php and page3.php which i have stored in my include folder and which i want to link to link1 when i click 2 on the paging button and 3 on the paging button. I have tried countless times but i'am unable to understand what i put in the 4 $which vars
    how i attach my $query_string and get_current_page. I'am not using mysql, and was not sure weather i needed to create an ul using category=sports as i saw in your source code. If possible can you help.

    • SachinKRaj May 25, 2011 at 10:10 am #

      @Norman:

      Could you please let me know the web page link where you are trying to implement this and also the script code, where I can look into the code of the page?

      If you want you can send me in email at: sachinkraj@gmail.com

    • Norman May 26, 2011 at 6:29 am #

      Hi Sachin,

      many thanks for replying. Webpage ls innerreach.co.cc and if you click on Link1 your paging method appears at the bottom of the page. I've sent you an email with more imformation.

      regards Norman.

      • SachinKRaj May 26, 2011 at 10:33 am #

        Norman:

        Now worries, I will help you out to work it for you.

        I have figured out the issue. Actually your site is already using a query variable called page in url. When I go Link1 and click on paging link, it gives me this link: http://innerreach.co.cc/?page=link1?page=3&ca… This is wrong link

        Problems with the above link:
        Any link should have only one (?) question mark, which indicates that the query string starts from here. Notice there are two question marks appending into url. I have made the changes in the method, so you do not need into code logic, see updated code below.
        Also notice that you are already using the query variable called "page", you should change the paging code. I have changed it to "showpage" in the updated code below.

        I have made the changes to the paging code, please update it with your site and try, if it works for you now and do let me know.

        Please see next comment:

      • SachinKRaj May 26, 2011 at 10:33 am #

        Here is the doPages() method new code:

        function doPages($page_size, $thepage, $query_string, $total=0) {

        //checks if the page link comes with pre set query string, if yes then start vars with & else with ?
        if (strstr($thepage, '?'){
        $thepage = $thepage . '&';
        }else{
        $thepage = $thepage . '?';
        }

        //per page count
        $index_limit = 10;

        //set the query string to blank, then later attach it with $query_string
        $query='';

        if(strlen($query_string)>0){
        $query = "&amp;".$query_string;
        }

        //get the current page number example: 3, 4 etc: see above method description
        $current = get_current_page();

        $total_pages=ceil($total/$page_size);
        $start=max($current-intval($index_limit/2), 1);
        $end=$start+$index_limit-1;

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

        if($current==1) {
        echo '<span class="prn">&lt; Previous</span>&nbsp;';
        } else {
        $i = $current-1;
        echo '<a href="'.$thepage.'showpage='.$i.$query.'" class="prn" rel="nofollow" title="go to page '.$i.'">&lt; Previous&nbsp;';
        echo '<span class="prn">…</span>&nbsp;';
        }

        if($start > 1) {
        $i = 1;
        echo '<a href="'.$thepage.'showpage='.$i.$query.'" title="go to page '.$i.'">'.$i.'&nbsp;';
        }

        for ($i = $start; $i <= $end && $i <= $total_pages; $i++){
        if($i==$current) {
        echo '<span>'.$i.'</span>&nbsp;';
        } else {
        echo '<a href="'.$thepage.'showpage='.$i.$query.'" title="go to page '.$i.'">'.$i.'&nbsp;';
        }
        }

        if($total_pages > $end){
        $i = $total_pages;
        echo '<a href="'.$thepage.'showpage='.$i.$query.'" title="go to page '.$i.'">'.$i.'&nbsp;';
        }

        if($current < $total_pages) {
        $i = $current+1;
        echo '<span class="prn">…</span>&nbsp;';
        echo '<a href="'.$thepage.'showpage='.$i.$query.'" class="prn" rel="nofollow" title="go to page '.$i.'">Next &gt;&nbsp;';
        } else {
        echo '<span class="prn">Next &gt;</span>&nbsp;';
        }

        //if nothing passed to method or zero, then dont print result, else print the total count below:
        if ($total != 0){
        //prints the total result count just below the paging
        echo '<p id="total_count">(total '.$total.' results)</div>';
        }

        }//end of method doPages()

  28. Bhaskar June 2, 2011 at 6:22 pm #

    Hi Sachin,

    I have tried to use the code with the data from mysql DB but in stead of showing the 10 result per page it is showing all the results. Also in my SQL query im trying to pass the variable which im getting from URL from another page. Below is the code which I'm trying to use.

    <?php

    include("include/connect.php");

    $sql = "SELECT * FROM log WHERE Activity = 'HTTP'";

    $result = mysql_query($sql) or die(mysql_error() . " " ."Error getting data.!!!");
    $total=mysql_num_rows($result);

    ?>
    <?PHP
    //This is the actual usage of function, It prints the paging links
    doPages(10, 'paging.php', '', $total);
    ?>

    <?php
    echo "<table border=1 align=center ><tr>";
    echo "<th>Date</th>";
    echo "<th>User</th>";
    echo "<th>Host</th>";
    echo "<th>Action</th></tr>";
    while ($row = mysql_fetch_assoc($result))
    {

    $Date=$row['Date'];
    $User=$row['User'];
    $Host=$row['Host'];
    $Action=$row['Action'];

    echo "<tr><td>$Date</td>";
    echo "<td>$User</td>";
    echo "<td>$Host</td>";
    echo "<td>$Action</td></tr>";
    }

    echo "</table>";
    ?>

    • Prashant June 2, 2011 at 8:23 pm #

      Hey Bhaskar, You need to make changes in your query. Currently you are selecting all the results, instead select only 10 results if you want to show the 10 results per page. This script only generates number of page links based on your results per page and total results you have in your db.

      Say I want have 100 results from a query, then I will run the 2 queries just like below:

      1. First one to get the total results we are getting, this will give us 100.

      SELECT COUNT(Id) FROM log WHERE Activity = 'HTTP';

      2. Then query to get results in PHP and show them

      SELECT * FROM log WHERE Activity = 'HTTP' LIMIT 0,10;

      Now this query for first page, for second page you need to make the LIMIT change to 10,20 and so on for other pages.

      Hope that will help you!

  29. kaushalpithadia June 26, 2011 at 11:15 am #

    Sachin,

    You had done a great job.

    I am just wondering why my code is not fetching only 10 rows per page.

    My database table consist of 67 rows, I am getting 7 page as per passing value to function

    doPages(10, 'paging.php', 'category=sports', $total_result);

    Upto this it is fine, but while display of page it showing all 67 records all to together, not showing 10 records and rest all according to the page.

    Please help and thanks in advance.
    Kaushal

  30. Christian June 26, 2011 at 11:02 pm #

    Thanks a Lot for this Code.. It helps me a lot..Easy to use.. easy to modify.. It was great..
    Thanks and Have a Blessed Day!

  31. Dinesh Gajjar August 25, 2011 at 1:57 pm #

    Thanks a lot !!
    This paging tutorial is very useful.
    Great ++++++++ job
    Good functionality and look of stylesheet.
    Thanks again.

  32. nadeem ehsan September 14, 2011 at 4:32 pm #

    can you please guide me how can i use this pagin
    e.x where can i put my query to show the records??

  33. cahyo September 26, 2011 at 12:57 pm #

    how to use your code ??
    I can integrate it with my database ?
    Thanks

  34. Sushil October 10, 2011 at 5:14 pm #

    wow

    really nice…….

  35. Miraz October 23, 2011 at 8:22 am #

    Mr. Sach

    Thanks for your tutorial.

    Can you tell me where to place the while loop in your script to display data from database.

  36. chintan November 7, 2011 at 5:02 pm #

    Nice paging

    • SachinKRaj November 7, 2011 at 5:14 pm #

      Thanks :)

      • chintan January 20, 2012 at 5:34 pm #

        plz give me a code for paging with edit update delete
        i try in ur code but i can only delete
        so plz give
        send me on
        c2n.2466@gmail.com
        k

  37. khushi November 17, 2011 at 2:20 pm #

    very nice paging………..

  38. fuad January 19, 2012 at 8:21 am #

    hey SachinKRaj I like u are code, can I use it for my code..:)

    • SachinKRaj January 19, 2012 at 10:24 am #

      Yes mate, without any obligations, that is why I am sharing it. Feel free to contact me if you face any issue.

  39. Muaz January 24, 2012 at 7:49 pm #

    nice work

  40. Joro January 29, 2012 at 10:30 pm #

    tnx, man, im really noob and this was excelent lesson to me :)

  41. vicos2 January 31, 2012 at 4:48 am #

    not absolutely understand how to combine it with db connection but the css is good

Leave a Reply