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 { buy cialis //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.

Related posts:

About Sach

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.

, , ,

  • Sushil Kumar Raghav

    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…

  • shubhamoy

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

  • ceema

    well done guys , keep it up

  • ceema

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

  • Gayash

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

  • Emese

    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.

  • key

    so, how to display my data from mysql?

    • SachinKRaj

      Key, Pelase read this tutorial:
      http://blog.sachinkraj.com/how-to-create-and-implement-paging-with-php-mysql/

      This will explain you everything you need to make paging with mysql.

  • Amalan

    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…

  • Mitx

    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);

    • SachinKRaj

      Mitx:

      I have added one more tutorial on the same, but along with implementations with mysql. Please refer to this tutorial:
      http://blog.sachinkraj.com/how-to-create-and-implement-paging-with-php-mysql/

      PS: Sorry for late response.

      • Vitalis

        Thanks so much sach
        I am having difficulty with the code on pagination. It was given me a parse error
        $index_limit = 10j
        Please can you tell me what to do to fix this.
        Regards,

        • SachinKRaj

          Could you please send me your code and the link where you are putting this script?
          You can email me your code at sachinkraj@gmail.com

  • Kunal

    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.

  • prashanth

    please give a easiest code for paging in php.

  • abhay

    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………..

    • SachinKRaj

      @Abhay:

      Can you please share a link of your script, where you are using the paging or the code file? I will try to fix it for you.

    • SachinKRaj

      Abhay: I have added one more tutorial on the same, but along with implementations with mysql. Please refer to this tutorial: http://blog.sachinkraj.com/how-to-create-and-implement-paging-with-php-mysql/

      PS: Sorry for late response.

  • zeek333

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

  • Jacop

    its realy great tutorial, thanks

  • lufti

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

  • rams

    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……..

  • Ankit

    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

  • @kaustubhkushte

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

  • Ndi Rustandi

    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=/

  • pavinz

    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

  • kamlesh

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

    • SachinKRaj

      Thanks a lot for appreciating :)

  • Andre

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

  • itman

    Great!!!!

  • daBruce

    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

      daBruce:

      Thanks a lot dear :)

  • Nikolius

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

    • SachinKRaj

      Thanks. :)

  • dawe

    Nice… Thanks!

  • Norman

    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

      @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

      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

        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

        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()

  • Bhaskar

    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

      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!

  • kaushalpithadia

    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

  • Christian

    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!

  • Dinesh Gajjar

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

  • nadeem ehsan

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

  • cahyo

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

  • Sushil

    wow

    really nice…….

  • Miraz

    Mr. Sach

    Thanks for your tutorial.

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

    • SachinKRaj

      Miraz,

      Today, I have posted one more tutorial, a script which will guide you on how you can use mysql table while developing paging. It has all things you needed like loop etc, Please read it here: http://blog.sachinkraj.com/how-to-create-simple-paging-with-php-css/

      Let me know if you need further help.
      Sach

  • chintan

    Nice paging

    • SachinKRaj

      Thanks :)

      • chintan

        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

  • khushi

    very nice paging………..

    • SachinKRaj

      Thanks Khushi

  • fuad

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

    • SachinKRaj

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

  • Muaz

    nice work

  • Joro

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

    • SachinKRaj

      You are welcome joro…. :)

  • vicos2

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

  • Php learner

    Hi Sachin. Thanks for this paging tutorial. I am using this tutorial but in a slightly different manner. I have used paging but I am using it with search functionality. Means I’m have a db table list of companies. Now I am searching all companies starting with letter say A, and all the companies with initial with A will appear. Now the problem is if there are say 100 companies with letter A, and I display 30 on one page and when I click on next or 2 it displays all the companies from database. So could you please help me in finding where is the problem in my code. 

    • Sachin Kumar Rajput

      You should use the doPages() function like this:

      doPages(10, ‘page.php’, ‘searchtext=A’, 123);

      searchtext=A will be added to your page URL

      Does this help? Let me know your page URL then I will let you know the exact params you need to pass to the doPages() function.

      • Php learner

        My page url is “localhost/companies/companyandjobs.php”. This page displays all jobs in the db table. Currently I have about 150 records in total in my db table. On this page I have a few search boxes for searching either by company or by position. So if I type developer, then my search results in 35 records. These 35 records are those companies which are looking for developer positions. I am showing about 30 records on one page. So it is divided into 2 pages. I am passing page number parameter like this ”
        localhost/companies/companyandjobs.php?page=1″ or ”
        localhost/companies/companyandjobs.php?page=2″. When I’m on the first page and I move cursor over 2 it shows ”
        localhost/companies/companyandjobs.php?page=2″. But when I click on two all results again come up which are 150. I have not changed anything below where you have written //NO NEED TO CHANGE ANYTHING IN CODE BELOW. Thanks for helping.

        • Sachin Kumar Rajput

          Looks like you are using POST for searching text. It would be good if you do it with GET method so the query string will add up in your URL like:

          localhost/companies/companyandjobs.php?page=2&query=companyA

          So this way your page will search all companies which are having string “companyA”, starting from record 11st because its page 2.

          Let me know if you need further assistance. Send me a demo/test script and mysql queries so that I can replicate this at my end and can fix it in code directly.

          • Php learner

            How can I send my demo/test script and other related things to you?

          • Php learner

            I mean any email id or anything?

          • Sachin Kumar Rajput

            Send me to sachinkraj@gmail.com

    • Sachin Kumar Rajput

      You should use the doPages() function like this:

      doPages(10, ‘page.php’, ‘searchtext=A’, 123);

      searchtext=A will be added to your page URL

      Does this help? Let me know your page URL then I will let you know the exact params you need to pass to the doPages() function.

  • Styx

    A nice pagination example I saw on http://www.cinemaboard.com/trailers.htm?offset=150
    Scroll down to the bottom to see it

  • pavelas boiko

    Hi everyone.
    I need help with this pagination the problem is very simple when i try to open index.php?page=2 but it doesn’t show index2.php?page=2 results in the page only index.php?page=1

    Why is this happening ?
    what am i doing so wrong ?
    I’m new so i need your help.
    I like this pagination and it is very to use and put in the page but as i said the problem with that.

    Where can i change to make work ?

    Thanks.

  • pavelas boiko

    Can you help me ?
    Can you look at the my site and see what i’m doing wrong ?
    Cuz i’m new for this your pagination and tried to change everywhere where there is paths for to make it work it doesn’t show index2.php?page=2 results what i have written for the test.

    • Sachin Kumar Rajput

      Could you please share the URL of the page where you are trying to implement this paging? Please share the link of page.

  • Nelio Romao

    Very nice and work like a charm.

    • Sachin Kumar Rajput

      Thanks :)

  • Rumibepari

    awesome… many many Thanks

  • Guest

    what if , i want to use it twice in a page ? top / bottom , 

  • Jignesh

     Such a wonderful paging.. i found very easy, but so helpfull, thank you very much…

    • Sachin Kumar Rajput

      Thanks jignesh :)

      • Jignesh

         But Sachin i have some problem regarding this can you please help me ?
        Pagination is not working in my code, all page display same results. is there any limit i have to set in my query ? like, ” $query = SELECT * FROM …. LIMIT $start , $end ” ? please help me..

        • Sachin Kumar Rajput

          Jignesh: Please mail me your script file at sachinkraj@gmail.com I shall check it.

          • Jignesh

             ok thanx. i am sending you …

          • Jignesh

            Ooh, it’s simple, i had solved my problem, Thank you very much for your precious time given to me, and reply to me… Thank you very much. Actually i am beginner , so found little problem. but thank you very much :-)

          • Sachin Kumar Rajput

            Oh that’s great! :)