Papermashup

Subscribe


Tweets


"RT @MagnificHQ: Dude miraculously saves his #drone from crashing into ocean in weird futuristic Baywatch scene http://t.co/FspY4TKES5 http:…"

@ashleyford 16 hours ago

"Thanks @KBedders @bethgordon @twitteruk for #BrandingMe! http://t.co/NNA2ke8NHc"

@ashleyford 1 day ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Easy PHP Pagination

Paginate results from a database using PHP

AshleyAshley

I’ve had a few pagination scripts over the years but I thought i’d share the one that i’m currently using as it’s a useful script to have in your toolbox. As a developer you’ll soon find a need to paginate data when displaying contents from the database, and rather than use JavaScript which could require all the data to be loaded into the page on load, we can use PHP to ensure that we’re only requesting the data that we need from the database. For those who have no clue what i’m talking about. Pagination is a way of splitting up data into manageable chunks to display to a user, if you’ve spent more than two minutes on the internet chances are you’ve come into contact with some form of pagination. as a simple example you can checkout my homepage, at the bottom you’ll see a list of page numbers allowing you to browse through pages of data, this script was originally written by the guys over at Stranger Studios and allows you to split data up with it being paginated across however many pages dynamically.

The Code

To start with you’ll see that we have our database connection file which we’re including into the page. Next you’ll see we’re setting three variables. ‘$tableName’, this refers to the table in your database that you want to get the data from, in our case it’s ‘countries_list’, ‘$targetpage’ refers to whatever you’ve saved the file as, in the case of the demo we’re saving the file as ‘index.php’. ‘$limit’ is the number of rows per page that we want to display from the database in the case of the demo you’ll see that we’re displaying just 10 rows.

Here are the main bullet points of what this file does in the simplest form.

  • Set the three variables at the top of the page declaring our database table, document filename, and number of results to display per page
  • Next we connect to the database and count the number of rows, so we know exactly how much data we’re dealing with
  • As the current page number is passed as a GET variable we check to see if a page number has been passed if there isn’t one then we set it to the first page
  • Then we have the query for the page content
  • Now we work out the next and previous page number as well as the last page number
  • Now we have a set of if statements, to determine which page the user is currently on relative to the total pages, so we can work out whether we need to display the first two page numbers with dots etc
  • Finally we echo ‘$paginate’ which will display our page numbers
  • Then we have our while loop which you can modify to suit your contents


include('connect.php');

$tableName="countries";
$targetpage = "index.php";
$limit = 10;

$query = "SELECT COUNT(*) as num FROM $tableName";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

$stages = 3;
$page = mysql_escape_string($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}

// Get page data
$query1 = "SELECT * FROM $tableName LIMIT $start, $limit";
$result = mysql_query($query1);

// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;

$paginate = '';
if($lastpage > 1)
{

$paginate .= "<div class='paginate'>";
// Previous
if ($page > 1){
$paginate.= "<a href='$targetpage?page=$prev'>previous</a>";
}else{
$paginate.= "<span class='disabled'>previous</span>"; }

// Pages
if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
}
elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few?
{
// Beginning only hide later pages
if($page < 1 + ($stages * 2))
{
for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
}
// Middle hide some front and some back
elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
{
$paginate.= "<a href='$targetpage?page=1'>1</a>";
$paginate.= "<a href='$targetpage?page=2'>2</a>";
$paginate.= "...";
for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
}
// End only hide early pages
else
{
$paginate.= "<a href='$targetpage?page=1'>1</a>";
$paginate.= "<a href='$targetpage?page=2'>2</a>";
$paginate.= "...";
for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
}
}

// Next
if ($page < $counter - 1){
$paginate.= "<a href='$targetpage?page=$next'>next</a>";
}else{
$paginate.= "<span class='disabled'>next</span>";
}

$paginate.= "</div>";

}
echo $total_pages.' Results';
// pagination
echo $paginate;

A bit of style

Here’s the css to style you pagination


.paginate {
font-family:Arial, Helvetica, sans-serif;
padding: 3px;
margin: 3px;
}

.paginate a {
padding:2px 5px 2px 5px;
margin:2px;
border:1px solid #999;
text-decoration:none;
color: #666;
}
.paginate a:hover, .paginate a:active {
border: 1px solid #999;
color: #000;
}
.paginate span.current {
margin: 2px;
padding: 2px 5px 2px 5px;
border: 1px solid #999;

font-weight: bold;
background-color: #999;
color: #FFF;
}
.paginate span.disabled {
padding:2px 5px 2px 5px;
margin:2px;
border:1px solid #eee;
color:#DDD;
}

li{
padding:4px;
margin-bottom:3px;
background-color:#FCC;
list-style:none;}

ul{margin:6px;
padding:0px;}

demodownload

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 113
  • Tuhin Hasan
    Posted on

    Tuhin Hasan Tuhin Hasan

    Reply Author

    Help Me: Notice: Use of undefined constant num – assumed ‘num’ in E:xampphtdocsppindex.php on line 68
    Notice: Undefined index: page in E:xampphtdocsppindex.php on line 71


  • wakil
    Posted on

    wakil wakil

    Reply Author

    very good paging


  • Tshering Wangchuk
    Posted on

    Tshering Wangchuk Tshering Wangchuk

    Reply Author

    Thanks for sharing…Great One…. Keep up the Good Work


  • Darshan
    Posted on

    Darshan Darshan

    Reply Author

    Please include the working principle also. Very good work though. Thanks Buddy.


  • proc
    Posted on

    proc proc

    Reply Author

    That’s so great, but how i can change sort by DESC? Now it’s older as first.


  • Meta3
    Posted on

    Meta3 Meta3

    Reply Author

    With a little modification this pagination is all that i need. Thank you, good job.


  • hamisi
    Posted on

    hamisi hamisi

    Reply Author

    thanx pals your codes work fine for me


  • Sarah
    Posted on

    Sarah Sarah

    Reply Author

    Thank you! I’m very grateful to your tutorial. :)


  • Donna Cerca Uomo Roma
    Posted on

    Donna Cerca Uomo Roma Donna Cerca Uomo Roma

    Reply Author

    It’s a little bit to big for me … I saw simpler pagination scripts


  • sachin
    Posted on

    sachin sachin

    Reply Author

    how to display this pagination in bottom instead of top of the records.


  • Rajendra Banker
    Posted on

    Rajendra Banker Rajendra Banker

    Reply Author

    Very useful code!
    Thanks


  • Joshua Balogun
    Posted on

    Joshua Balogun Joshua Balogun

    Reply Author

    Thanks, So awesome and easy.


  • RentForge
    Posted on

    RentForge RentForge

    Reply Author

    thanx a lot for this script…. I will use it in my next project…..
    presently I am working on http://rentforge.in it may also help in this also….
    once again thanx a lot :)


  • Jose Niño Garcia
    Posted on

    Jose Niño Garcia Jose Niño Garcia

    Reply Author

    Hi there, thank you so much, at first I got the problem on the code but when I fixed the mysql_real_escape_string, it worked!


  • Satyaranjan
    Posted on

    Satyaranjan Satyaranjan

    Reply Author

    thanx


  • AQ SHAFI
    Posted on

    AQ SHAFI AQ SHAFI

    Reply Author

    I used this script its nice, Thanks for sharing. can we manage pagination like this, suppose we are on page 10 show the backup record like we show 10 item on per page, when we are on 10 no page he show me record 1 of 100.

    Thank You.


  • Kaysellers
    Posted on

    Kaysellers Kaysellers

    Reply Author

    Hello GUys,

    Awesome work. Really perfect. GOnna use in my next project.


  • Mohammad Raihan Mazumder
    Posted on

    Mohammad Raihan Mazumder Mohammad Raihan Mazumder

    Reply Author

    http://www.creativekube.com/topupbd/index.html
    user: admin
    pass: admin

    PAGINATION LINK: Complete History, Pending History & Cancel History
    —————————————–

    please help me out to finished pagination:
    <?php

    function paginate_three($reload, $page, $tpages, $adjacents) {

    $prevlabel = "‹ Prev";
    $nextlabel = "Next ›";

    $out = "n”;

    // previous
    if($page==1) {
    $out.= “” . $prevlabel . “n”;
    }
    elseif($page==2) {
    $out.= “” . $prevlabel . “n”;
    }
    else {
    $out.= “” . $prevlabel . “n”;
    }

    // first
    if($page>($adjacents+1)) {
    $out.= “1n”;
    }

    // interval
    if($page>($adjacents+2)) {
    $out.= “…n”;
    }

    // pages
    $pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
    $pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
    for($i=$pmin; $i<=$pmax; $i++) {
    if($i==$page) {
    $out.= "” . $i . “n”;
    }
    elseif($i==1) {
    $out.= “” . $i . “n”;
    }
    else {
    $out.= “” . $i . “n”;
    }
    }

    // interval
    if($page<($tpages-$adjacents-1)) {
    $out.= "…n";
    }

    // last
    if($page<($tpages-$adjacents)) {
    $out.= "” . $tpages . “n”;
    }

    // next
    if($page<$tpages) {
    $out.= "” . $nextlabel . “n”;
    }
    else {
    $out.= “” . $nextlabel . “n”;
    }

    $out.= “”;

    return $out;
    }
    ?>

    <?php

    $rpp = 50; // results per page
    $adjacents = 4;

    $page = intval($_GET["page"]);
    if($page<=0) $page = 1;

    $reload = $_SERVER['PHP_SELF'];

    // select appropriate results from DB:
    $sql = "SELECT * FROM 'topup' ".$pagestatus." ORDER BY field_name";
    $result = mysql_query($sql, $link_id);

    // count total number of appropriate listings:
    $tcount = mysql_num_rows($result);

    // count number of pages:
    $tpages = ($tcount) ? ceil($tcount/$rpp) : 100; // total pages, last page number

    $count = 0;
    $i = ($page-1)*$rpp;
    while(($count<$rpp) && ($i<$tcount)) {
    mysql_data_seek($result,$i);
    $query = mysql_fetch_array($result);

    // output each row:
    echo "” . $query[‘table_field_1′] . “, ” . $query[‘table_field_2′] . “n”;

    $i++;
    $count++;
    }

    ?>


  • Mohammad Raihan Mazumder
    Posted on

    Mohammad Raihan Mazumder Mohammad Raihan Mazumder

    Reply Author

    http://www.creativekube.com/topupbd/index,html
    user: admin
    pass: admin

    Please help me to solve out this pagination code:
    <?php

    function paginate_three($reload, $page, $tpages, $adjacents) {

    $prevlabel = "‹ Prev";
    $nextlabel = "Next ›";

    $out = "n”;

    // previous
    if($page==1) {
    $out.= “” . $prevlabel . “n”;
    }
    elseif($page==2) {
    $out.= “” . $prevlabel . “n”;
    }
    else {
    $out.= “” . $prevlabel . “n”;
    }

    // first
    if($page>($adjacents+1)) {
    $out.= “1n”;
    }

    // interval
    if($page>($adjacents+2)) {
    $out.= “…n”;
    }

    // pages
    $pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
    $pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
    for($i=$pmin; $i<=$pmax; $i++) {
    if($i==$page) {
    $out.= "” . $i . “n”;
    }
    elseif($i==1) {
    $out.= “” . $i . “n”;
    }
    else {
    $out.= “” . $i . “n”;
    }
    }

    // interval
    if($page<($tpages-$adjacents-1)) {
    $out.= "…n";
    }

    // last
    if($page<($tpages-$adjacents)) {
    $out.= "” . $tpages . “n”;
    }

    // next
    if($page<$tpages) {
    $out.= "” . $nextlabel . “n”;
    }
    else {
    $out.= “” . $nextlabel . “n”;
    }

    $out.= “”;

    return $out;
    }
    ?>

    <?php

    $rpp = 50; // results per page
    $adjacents = 4;

    $page = intval($_GET["page"]);
    if($page<=0) $page = 1;

    $reload = $_SERVER['PHP_SELF'];

    // select appropriate results from DB:
    $sql = "SELECT * FROM 'topup' ".$pagestatus." ORDER BY field_name";
    $result = mysql_query($sql, $link_id);

    // count total number of appropriate listings:
    $tcount = mysql_num_rows($result);

    // count number of pages:
    $tpages = ($tcount) ? ceil($tcount/$rpp) : 100; // total pages, last page number

    $count = 0;
    $i = ($page-1)*$rpp;
    while(($count<$rpp) && ($i<$tcount)) {
    mysql_data_seek($result,$i);
    $query = mysql_fetch_array($result);

    // output each row:
    echo "” . $query[‘table_field_1′] . “, ” . $query[‘table_field_2′] . “n”;

    $i++;
    $count++;
    }

    ?>


  • Mihai
    Posted on

    Mihai Mihai

    Reply Author

    Hi there, I’ve also wrote an tutorial about how to paginate database results usign PHP. I’ve wrote a PHP function which can be used very easy. Please read it at http://www.lampcoder.com/how-to-paginate-mysql-database-results-using-php-function/


  • Jeff
    Posted on

    Jeff Jeff

    Reply Author

    I was wondering if you had a little something for me to work with using variables instead of mqsql?

    Here is a snippet of what I have and would like to make this paginate.

    ?>

    <img src="” height=”40″ width=”40″ alt=”” />

     / <?=$vUnit['sizeX'] ” ? $vUnit[‘sizeX’] . ‘x’ . $vUnit[‘sizeY’] : ‘-‘; ?> / 

    <input type="hidden" id="sellst__qty” value=”” />

    <input type="text" name="” size=”4″ />

    <?php

    Any help is greatly appreciated :)


  • ramkumar
    Posted on

    ramkumar ramkumar

    Reply Author

    ithu peru easy aana coding ah?poi easy na enna nu dictionary le theduda crack….


  • ramkumar
    Posted on

    ramkumar ramkumar

    Reply Author

    ey its nice..thanx for sharing…


  • ramkumar
    Posted on

    ramkumar ramkumar

    Reply Author

    poda goyya…is this an easy code?un moonchiyum neeyum….


  • B
    Posted on

    B B

    Reply Author

    Thank you for sharing your work with us.


  • games
    Posted on

    games games

    Reply Author

    This is really helpful,thank you…..


  • waqas umar
    Posted on

    waqas umar waqas umar

    Reply Author

    hey thanks man, it worked for me :) really thankyou , stay safe .


  • Waseem
    Posted on

    Waseem Waseem

    Reply Author

    Works Perfect.
    Thanks Alot :)


  • sanina
    Posted on

    sanina sanina

    Reply Author

    Честно у вас хуйня а не пагницая запросы для построения по странички это тупо лучше использовать методы без mysql
    Например сперва сделать

    $start = 0;
    $limit = 5;
    SELECT SQL_CALC_FOUND_ROWS * FROM MYTABLE LIMIT $limit;
    ВЫВЕСТИ ДАННЫЕ

    А что бы узнать сколько осталось следом выполнить
    $result = $pdo->prepare(“SELECT FOUND_ROWS() AS count”);
    $result->execute();
    $count = $result->fetch(PDO::FETCH_ASSOC);
    print $count[‘count’];

    Что бы узнать сколько страниц у нас? не трудно посчитать

    $countPages = ceil($count[‘count’] / $limit);

    D j,otv ujcgjlf fvbhbrjcs 2 dfv


  • Art
    Posted on

    Art Art

    Reply Author

    Calling this “easy” is a bit ridiculous. It’s a lot easier than that.


  • viddz
    Posted on

    viddz viddz

    Reply Author

    wow this is awsum. simplicity of this script impressed me a lot. Thanks for shairing


  • Stephen
    Posted on

    Stephen Stephen

    Reply Author

    plz, help me,How add link like : First | Prev 1 2 3 4 Last | Next


  • jeffs
    Posted on

    jeffs jeffs

    Reply Author

    I have to said it loud “THANK YOU”

    Your script are perfect and very good explaination. You are definately one of the best.

    Keep it up.


  • ilavenil
    Posted on

    ilavenil ilavenil

    Reply Author

    Hi,
    This tutorial is really helpful. Thanks!!!
    But i have an issue with $page = mysql_escape_string($_GET[‘page’]);
    The page says: Notice: Undefined index: page
    if i go to the next page then come back to the first page, i don’t see this error.
    Please guide me how to eliminate this problem…

    Thanks again!!!


  • Kanny
    Posted on

    Kanny Kanny

    Reply Author

    Thank you so much!
    This is a on of easiest example for PHP learner…
    It solve my problem quickly


  • Madhusudhan
    Posted on

    Madhusudhan Madhusudhan

    Reply Author

    Hi,

    I have saved my youtube link in my db,and trying to retrieve it to my website using pagination.

    {[$row[‘ylink’]]} // ylink is the youtube link

    i used as above but its not helping me.

    Please support ,how can i get it?


  • birender
    Posted on

    birender birender

    Reply Author

    thanks a lot…ur script help me a lot…..


  • Madhusudhan
    Posted on

    Madhusudhan Madhusudhan

    Reply Author

    Thanks for sharing ….


  • Peter
    Posted on

    Peter Peter

    Reply Author

    Thank you, you have help me very much :)


  • aman
    Posted on

    aman aman

    Reply Author

    this pagination is great and working properly in simple phpmysql queries but for search query it is not working ….
    plz help

    <?php
    include("config.php");
    ini_set("display_errors",0);

    if(isset($_POST['search']))
    {

    $pro_for=$_POST["pro_for"];

    $pro_cat=$_SESSION['pro_cat'];

    $pro_type=$_POST["pro_type"];
    $city=$_POST["city"];
    $city=$_POST["city"];
    if($pro_cat=='')
    {

    echo'alert(“Please select Property category.”);window.location=”index.php”;';

    }
    elseif($pro_type==”)
    {

    echo’alert(“Please select Property type.”);window.location=”index.php”;';

    }
    elseif($city==”)
    {

    echo’alert(“Please select city.”);window.location=”index.php”;';

    }
    elseif($pro_for==”)
    {

    echo’alert(“Please select property you want for.”);window.location=”index.php”;';

    }
    else
    {
    $pro_for=$_POST[“pro_for”];
    $pro_cat=$_POST[“pro_cat”];
    $pro_type=$_POST[“pro_type”];
    $city=$_POST[“city”];
    $area=$_POST[“area”];
    $min_buget=$_POST[“min_buget”];
    $max_buget=$_POST[“max_buget”];

    if($pro_for!==” && $pro_cat!=”&& $pro_type!=”&&$city!=”&&$area!=”&& $max_buget==”&& $min_buget==”)
    {
    $tableName=”property”;
    $targetpage = ‘index.php?c=search-results';
    $limit = 1;
    $query2=”select COUNT(*) as num from $tableName where pro_for='”.$pro_for.”‘ and cat='”.$pro_cat.”‘ and pro_type='”.$pro_type.”‘ and city='”.$city.”‘ and area='”.$area.”‘”;
    $query = $query2;
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];

    $stages = 3;
    $page = mysql_escape_string($_GET[‘page’]);
    if($page){
    $start = ($page – 1) * $limit;
    }else{
    $start = 0;
    }

    // Get page data
    echo $query1=”select * FROM $tableName where pro_for='”.$pro_for.”‘ and cat='”.$pro_cat.”‘ and pro_type='”.$pro_type.”‘ and city='”.$city.”‘ and area='”.$area.”‘ LIMIT $start, $limit”;
    $result = mysql_query($query1);

    // Initial page num setup
    if ($page == 0){$page = 1;}
    $prev = $page – 1;
    $next = $page + 1;
    $lastpage = ceil($total_pages/$limit);
    $LastPagem1 = $lastpage – 1;

    $paginate = ”;

    }
    elseif($pro_for!==” && $pro_cat!=”&& $pro_type!=”&&$city!=”&&$area!=”&& $max_buget==!”&& $min_buget==!”)
    {
    $tableName=”property”;
    $targetpage = ‘index.php?c=search-results';
    $limit = 1;
    $query2=”select COUNT(*) as num from $tableName where pro_for='”.$pro_for.”‘ and cat='”.$pro_cat.”‘ and pro_type='”.$pro_type.”‘ and city='”.$city.”‘ and area='”.$area.”‘ and exp_rate BETWEEN ‘”.$_POST[‘min_buget’].”‘ and ‘”.$_POST[‘max_buget’].”‘”;

    $query = $query2;
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];

    $stages = 2;
    $page = mysql_escape_string($_GET[‘page’]);
    if($page){
    $start = ($page – 1) * $limit;
    }else{
    $start = 0;
    }

    // Get page data
    echo $query1=”select * FROM $tableName where pro_for='”.$pro_for.”‘ and cat='”.$pro_cat.”‘ and pro_type='”.$pro_type.”‘ and city='”.$city.”‘ and area='”.$area.”‘ and exp_rate BETWEEN ‘”.$_POST[‘min_buget’].”‘ and ‘”.$_POST[‘max_buget’].”‘ LIMIT $start, $limit”;
    $result = mysql_query($query1);

    // Initial page num setup
    if ($page == 0){$page = 1;}
    $prev = $page – 1;
    $next = $page + 1;
    $lastpage = ceil($total_pages/$limit);
    $LastPagem1 = $lastpage – 1;

    $paginate = ”;

    }

    }

    }

    ?>

    searched data to comes here

    1)
    {

    $paginate .= “”;
    // Previous
    if ($page > 1){
    $paginate.= “previous“;
    }else{
    $paginate.= “previous”; }

    // Pages
    if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up
    {
    for ($counter = 1; $counter <= $lastpage; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{
    $paginate.= “$counter“;}
    }
    }
    elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few?
    {
    // Beginning only hide later pages
    if($page < 1 + ($stages * 2))
    {
    for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{
    $paginate.= “$counter“;}
    }
    $paginate.= “…”;
    $paginate.= “$LastPagem1“;
    $paginate.= “$lastpage“;
    }
    // Middle hide some front and some back
    elseif($lastpage – ($stages * 2) > $page && $page > ($stages * 2))
    {
    $paginate.= “1“;
    $paginate.= “2“;
    $paginate.= “…”;
    for ($counter = $page – $stages; $counter <= $page + $stages; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{
    $paginate.= “$counter“;}
    }
    $paginate.= “…”;
    $paginate.= “$LastPagem1“;
    $paginate.= “$lastpage“;
    }
    // End only hide early pages
    else
    {
    $paginate.= “1“;
    $paginate.= “2“;
    $paginate.= “…”;
    for ($counter = $lastpage – (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{
    $paginate.= “$counter“;}
    }
    }
    }

    // Next
    if ($page < $counter – 1){
    $paginate.= "next“;
    }else{
    $paginate.= “next”;
    }

    $paginate.= “”;

    }
    $total_pages.’ Results';
    // pagination
    echo $paginate;
    ?>

    plz help me


  • ines
    Posted on

    ines ines

    Reply Author

    I applied this code.since display data is displayed only the data from the first page (lines <limit). So the following pages do not display anything
    can you help me please
    thank you for the tutoriels


  • Brittney
    Posted on

    Brittney Brittney

    Reply Author

    Thank you SO SO SO SO much! This was a HUGE help, and I really appreciate you posting this! Best pagination I’ve seen :)


  • Aman Tilak
    Posted on

    Aman Tilak Aman Tilak

    Reply Author

    Thanks a lot…..
    you make pagination problem simple and easier for me…..
    now no tension for placing pagination ….
    thanx once again


  • chinju
    Posted on

    chinju chinju

    Reply Author

    Hi,
    This is Great and simple script…Thanks for sharing it.
    If i need to add ‘first and last’ option before and after ‘previous and next’ button, what will be the changes in code??


  • Bill
    Posted on

    Bill Bill

    Reply Author

    Hi,

    When I call the page with the pagination from a form submit, the query (select statement) is built from the form data.

    The first page and count is correct but If I click on any of the page navigation #s or next/previous, the select statement is not stored between and the results defaults to all records.

    Any ideas on how to prevent this?

    Thanks.


  • Raja
    Posted on

    Raja Raja

    Reply Author

    Thank You so much ! been so useful and easy to use this pagination code !
    Thanks again :)


  • Suneel Pervaiz
    Posted on

    Suneel Pervaiz Suneel Pervaiz

    Reply Author

    very nice post dude thanks ……


  • Nick
    Posted on

    Nick Nick

    Reply Author

    This is THE easiest and simplest tutorial I’ve seen on pagination till date.

    Awesome job man! Works like a charm and super easy to plug in.


  • sam
    Posted on

    sam sam

    Reply Author

    Here is my version of pagination, if you go to http://www.jadremtoys.com.au/catalogue/toy-group.php?grpid=141&name=Barbie-Collector you’ll see the the “grpid = 141″ this paramater is used in the $tableName=”view_catgrpitemlist”

    1)
    {

    $paginate .= “”;
    // Previous
    if ($page > 1){
    if ($page ==2 ){
    $paginate.= “previous“;
    }else{
    $paginate.= “previous“;
    }
    }else{
    $paginate.= “previous”; }

    // Pages
    if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up
    {
    for ($counter = 1; $counter <= $lastpage; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{
    if ($counter ==1 ){
    $paginate.= “$counter“;
    }else{
    $paginate.= “$counter“;
    }
    }
    }
    }
    elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few?
    {
    // Beginning only hide later pages
    if($page < 1 + ($stages * 2))
    {
    $paginate.= "1“;
    for ($counter = 2; $counter < 4 + ($stages * 2); $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{

    $paginate.= “$counter“;
    }
    }
    $paginate.= “…”;
    $paginate.= “$LastPagem1“;
    $paginate.= “$lastpage“;
    }
    // Middle hide some front and some back
    elseif($lastpage – ($stages * 2) > $page && $page > ($stages * 2))
    {
    $paginate.= “1“;
    $paginate.= “2“;
    $paginate.= “…”;
    for ($counter = $page – $stages; $counter <= $page + $stages; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{

    $paginate.= “$counter“;
    }
    }
    $paginate.= “…”;
    $paginate.= “$LastPagem1“;
    $paginate.= “$lastpage“;
    }
    // End only hide early pages
    else
    {
    $paginate.= “1“;
    $paginate.= “2“;
    $paginate.= “…”;
    for ($counter = $lastpage – (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
    {
    if ($counter == $page){
    $paginate.= "$counter”;
    }else{

    $paginate.= “$counter“;
    }
    }
    }
    }

    // Next
    if ($page < $counter – 1){
    $paginate.= "next“;
    }else{
    $paginate.= “next”;
    }

    $paginate.= “”;

    }
    echo $total_pages.’ Results';
    // pagination
    echo $paginate;
    ?>


  • sam
    Posted on

    sam sam

    Reply Author

    Hi David, yes it can be done, go to our childrens toys site http://www.jadremtoys.com.au. The category menu on the left will deliver paginated results, a menu is just like a search it provides the database with a parameter

    Cheers
    Sam


  • David
    Posted on

    David David

    Reply Author

    Thanks for a great tutorial! When I do a search and paginate the results everything looks great. When I click on any of the paginated pages, though, the whole database is returned. Is there anyway to paginate through a found set that was based on a search from a form input?

    Thanks,

    David


  • pico
    Posted on

    pico pico

    Reply Author

    When first time browse i got this error “Notice: Undefined index: page in” if click pagination it’s disapper


  • pico
    Posted on

    pico pico

    Reply Author

    “Notice: Undefined index: page in” first time browse how can i fix it


  • faisal
    Posted on

    faisal faisal

    Reply Author

    thanks for sharing… It really helped me to get rid of headache, caused to do pagination.


  • Sam
    Posted on

    Sam Sam

    Reply Author

    Code needs slight change, just ran MS site analysis report over my site, it picks up the initial page say “catalogue” and when you go back and via the paginator to page 1 the href is catalogue&page=1.

    Site analysis reports it as a multiple canonical, catalogue and catalogue&page=1 being the same page.

    When we go back to page one it should drop the page=1

    cheers


  • Sam
    Posted on

    Sam Sam

    Reply Author

    If you want the pagination images at the bottom of your list just move the code for the repeating loop above the pagination code

    http://www.jadremtoys.com.au/catalogue/toy-group.php?grpid=101&name=Action-Figures-And-Toys

    cheers


  • Sam
    Posted on

    Sam Sam

    Reply Author

    Very much appreciated, had to play around a bit suit our needs – works well looks good

    http://www.jadremtoys.com.au/catalogue/toy-group.php?grpid=99&name=Music-Boxes

    Cheers
    Sam


  • aixa
    Posted on

    aixa aixa

    Reply Author

    Thanks for sharing. u very helpful.Excellent


  • Prasad
    Posted on

    Prasad Prasad

    Reply Author

    A great stuff..a simple and easy way to handle pagination .Thanks for the article.


  • zack
    Posted on

    zack zack

    Reply Author

    Nicely done. one thing i like to ask. how can i add the pagination to bottom of the page? thanks


  • surf
    Posted on

    surf surf

    Reply Author

    Hi,
    The form that i am using is on a different page eg testpage and the results are to be displayed on testresults .. when submit is clicked the first testresults page is fine but then the links do not work.
    i am guessing ths is because of
    $page = mysql_escape_string($_GET[‘page’]);
    any advice will be helpful?


  • Ed
    Posted on

    Ed Ed

    Reply Author

    Hi ashley,

    Thanks for the great post.. However, im getting this error.. dont know why.. see below

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:PHPpaginationindex.php on line 67

    Notice: Use of undefined constant num – assumed ‘num’ in C:PHPpaginationindex.php on line 68

    Notice: Undefined index: page in C:PHPpaginationindex.php on line 71
    Results

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:PHPpaginationindex.php on line 187

    It refers to this line
    $total_pages = $total_pages[num];

    and this line

    $page = mysql_escape_string($_GET[‘page’]);

    Im confused.. Help please.. thanks ashley.. :)


  • Martin
    Posted on

    Martin Martin

    Reply Author

    Excellent, thanks!


  • Cocinar
    Posted on

    Cocinar Cocinar

    Reply Author

    Thatś great, I’m changing my script from Wp to a mine from the scracth and comes perfect this pagination, thank you for the tutorial!


  • Osama
    Posted on

    Osama Osama

    Reply Author

    This Is The Best Class I Ever So

    Thanks For Sharing

    How Can I Make The Number Show

    Right To Left

    Instead Of

    Left To Right ?


  • kashif farooq
    Posted on

    kashif farooq kashif farooq

    Reply Author

    display records from dbase page wise in php, page numbers should be displayed in a drop down combo box (using ). instead of like this: page numbers 1, 2, 3, …. till last.


  • DC Web Design
    Posted on

    DC Web Design DC Web Design

    Reply Author

    Thanks for this awesome solution . Great tut.


  • Belask
    Posted on

    Belask Belask

    Reply Author

    Thanks. Very nice tutorial.


  • Dan
    Posted on

    Dan Dan

    Reply Author

    Thanks so much!


  • Yusuf Tokgöz
    Posted on

    Yusuf Tokgöz Yusuf Tokgöz

    Reply Author

    absolutely great and easiest tutorial in the whole net. I needed one and here it is in my website you can check the result http://www.turkishpropertiesabroad.com
    it paginates the houses…
    Thanx Man


  • sms
    Posted on

    sms sms

    Reply Author

    amazing and easy pagination , hats off :)


  • Vipin
    Posted on

    Vipin Vipin

    Reply Author

    Thanks Ashley, the code worked perfect. Only one question, when I changed the SQL query to $query = SELECT COUNT(*) as num FROM $tableName order by ID DESC it didn’t work. Please let me know how to fix this. The results are displayed random because of this.

    Again Thanks


  • curtis
    Posted on

    curtis curtis

    Reply Author

    hi i have used your script and when there are more than 10 results it displays a link to the next page but there are more than 10 results appearing on the page and the same results on the second page without splitting them, any help with this problem please


  • Qaysar
    Posted on

    Qaysar Qaysar

    Reply Author

    Hello,

    Just downloaded the files and they are corrupt also when viewing this website I get the code displayed ina funny way.

    &lt;?php

    002 include(‘connect.php’);

    003

    004 $tableName=&quot;countries_list&quot;;

    005 $targetpage = &quot;index.php&quot;;

    006 $limit = 10;

    007

    008 $query = &quot;SELECT COUNT(*) as num FROM $tableName&quot;;

    009 $total_pages = mysql_fetch_array(mysql_query($query));

    010 $total_pages = $total_pages[num];

    011

    012 $stages = 3;

    013 $page = mysql_escape_string($_GET[‘page’]);

    014 if($page){

    015 $start = ($page – 1) * $limit;

    016 }else{

    017 $start = 0;

    018 }

    019

    020 // Get page data

    021 $query1 = &quot;SELECT * FROM $tableName LIMIT $start, $limit&quot;;

    022 $result = mysql_query($query1);

    023

    024 // Initial page num setup

    025 if ($page == 0){$page = 1;}

    026 $prev = $page – 1;

    027 $next = $page + 1;

    028 $lastpage = ceil($total_pages/$limit);

    029 $LastPagem1 = $lastpage – 1;

    030

    031 $paginate = ”;

    032 if($lastpage &gt; 1)

    033 {

    034

    035 $paginate .= &quot;&lt;div class=’paginate’&gt;&quot;;

    036 // Previous

    037 if ($page &gt; 1){

    038 $paginate.= &quot;&lt;a href=’$targetpage?page=$prev’&gt;previous&lt;/a&gt;&quot;;

    039 }else{

    040 $paginate.= &quot;&lt;span class=’disabled’&gt;previous&lt;/span&gt;&quot;; }

    041

    042 // Pages

    043 if ($lastpage &lt; 7 + ($stages * 2)) // Not enough pages to breaking it up

    044 {

    045 for ($counter = 1; $counter &lt;= $lastpage; $counter++)

    046 {

    047 if ($counter == $page){

    048 $paginate.= &quot;&lt;span class=’current’&gt;$counter&lt;/span&gt;&quot;;

    049 }else{

    050 $paginate.= &quot;&lt;a href=’$targetpage?page=$counter’&gt;$counter&lt;/a&gt;&quot;;}

    051 }

    052 }

    053 elseif($lastpage &gt; 5 + ($stages * 2)) // Enough pages to hide a few?

    054 {

    055 // Beginning only hide later pages

    056 if($page &lt; 1 + ($stages * 2))

    057 {

    058 for ($counter = 1; $counter &lt; 4 + ($stages * 2); $counter++)

    059 {

    060 if ($counter == $page){

    061 $paginate.= &quot;&lt;span class=’current’&gt;$counter&lt;/span&gt;&quot;;

    062 }else{

    063 $paginate.= &quot;&lt;a href=’$targetpage?page=$counter’&gt;$counter&lt;/a&gt;&quot;;}

    064 }

    065 $paginate.= &quot;…&quot;;

    066 $paginate.= &quot;&lt;a href=’$targetpage?page=$LastPagem1’&gt;$LastPagem1&lt;/a&gt;&quot;;

    067 $paginate.= &quot;&lt;a href=’$targetpage?page=$lastpage’&gt;$lastpage&lt;/a&gt;&quot;;

    068 }

    069 // Middle hide some front and some back

    070 elseif($lastpage – ($stages * 2) &gt; $page &amp;&amp; $page &gt; ($stages * 2))

    071 {

    072 $paginate.= &quot;&lt;a href=’$targetpage?page=1’&gt;1&lt;/a&gt;&quot;;

    073 $paginate.= &quot;&lt;a href=’$targetpage?page=2’&gt;2&lt;/a&gt;&quot;;

    074 $paginate.= &quot;…&quot;;

    075 for ($counter = $page – $stages; $counter &lt;= $page + $stages; $counter++)

    076 {

    077 if ($counter == $page){

    078 $paginate.= &quot;&lt;span class=’current’&gt;$counter&lt;/span&gt;&quot;;

    079 }else{

    080 $paginate.= &quot;&lt;a href=’$targetpage?page=$counter’&gt;$counter&lt;/a&gt;&quot;;}

    081 }

    082 $paginate.= &quot;…&quot;;

    083 $paginate.= &quot;&lt;a href=’$targetpage?page=$LastPagem1’&gt;$LastPagem1&lt;/a&gt;&quot;;

    084 $paginate.= &quot;&lt;a href=’$targetpage?page=$lastpage’&gt;$lastpage&lt;/a&gt;&quot;;

    085 }

    086 // End only hide early pages

    087 else

    088 {

    089 $paginate.= &quot;&lt;a href=’$targetpage?page=1’&gt;1&lt;/a&gt;&quot;;

    090 $paginate.= &quot;&lt;a href=’$targetpage?page=2’&gt;2&lt;/a&gt;&quot;;

    091 $paginate.= &quot;…&quot;;

    092 for ($counter = $lastpage – (2 + ($stages * 2)); $counter &lt;= $lastpage; $counter++)

    093 {

    094 if ($counter == $page){

    095 $paginate.= &quot;&lt;span class=’current’&gt;$counter&lt;/span&gt;&quot;;

    096 }else{

    097 $paginate.= &quot;&lt;a href=’$targetpage?page=$counter’&gt;$counter&lt;/a&gt;&quot;;}

    098 }

    099 }

    100 }

    101

    102 // Next

    103 if ($page &lt; $counter – 1){

    104 $paginate.= &quot;&lt;a href=’$targetpage?page=$next’&gt;next&lt;/a&gt;&quot;;

    105 }else{

    106 $paginate.= &quot;&lt;span class=’disabled’&gt;next&lt;/span&gt;&quot;;

    107 }

    108

    109 $paginate.= &quot;&lt;/div&gt;&quot;;

    110

    111 }

    112 echo $total_pages.’ Results';

    113 // pagination

    114 echo $paginate;

    115 ?&gt;

    116

    117 &lt;ul&gt;

    118

    119 &lt;?php

    120

    121 while($row = mysql_fetch_array($result))

    122 {

    123

    124 echo ‘&lt;li&gt;’.$row[‘country’].’&lt;/li&gt;';

    125

    126 }

    127

    128 ?&gt;

    129 &lt;/ul&gt;

    Thats the code I get when viewing, does anyone have an ammended version to this please.

    My email is [email protected]

    Thank you


  • Rajendra
    Posted on

    Rajendra Rajendra

    Reply Author

    Nice Post dude


  • klb
    Posted on

    klb klb

    Reply Author

    thank u soo much .its working perfectly


  • alan
    Posted on

    alan alan

    Reply Author

    great stuff, but how would you link in a search form?


  • Pramod
    Posted on

    Pramod Pramod

    Reply Author

    Thanks a lot. You saved my day.


  • Hayder Abbass
    Posted on

    Hayder Abbass Hayder Abbass

    Reply Author

    Nice article Ashley .nowadays there’s another sort of pagination similar to facebook and twitter .
    it’s worth reading , see it guys
    http://youhack.me/2010/05/14/an-alternative-to-pagination-facebook-and-twitter-style/


  • roma2509
    Posted on

    roma2509 roma2509

    Reply Author

    Hello.I optain the “Notice: Undefined index: page in C:wampwwwtop50brandsindex.php on line 13″
    What its wrong?


  • newb
    Posted on

    newb newb

    Reply Author

    ya i am new to php and html … can some explain why these “&quot;countries_list&quot;” are part of every single line …. does that not confused developer …


  • redesign soft
    Posted on

    redesign soft redesign soft

    Reply Author

    Thanks for this. It is working very well


  • Hridayz
    Posted on

    Hridayz Hridayz

    Reply Author

    Hey dude,
    its a great site.. Each of the contents are quite intresting. well done dude..


  • neil coutinho
    Posted on

    neil coutinho neil coutinho

    Reply Author

    Thx a lot Ashley it worked perfectly


  • Sam
    Posted on

    Sam Sam

    Reply Author

    Fantastic script, works perfectly, thanks for that.
    That’s exactly what I was looking for! :-)


  • Neil
    Posted on

    Neil Neil

    Reply Author

    Thanks for this, works perfectly and is by far the easiest to use!!!


  • kiko
    Posted on

    kiko kiko

    Reply Author

    good but nit great there are some bugs


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Kiko, There are no bugs in the script. It works straight out of the box. Check the demo out.


  • johnm
    Posted on

    johnm johnm

    Reply Author

    Easy? I don’t find this to really be much easy I guess since I’ve been using a php mvc framework for about 4 months now. It’s a great post and I thank you for your contribution. Here’s something others might want to look at using MVC frameworks.

    // function to call
    function get_limit_and_offset($per_page, $page_number)
    {
    if($page_number < 1)
    {
    $page_number = 1;
    }
    $pagination['limit'] = $per_page;
    $pagination['offset'] = ($page_number * $per_page) - $per_page;
    return $pagination;
    }
    // give function data
    $pagination_data = get_limit_and_offset($per_page, $page_number);

    // query thats used
    mysql_query("SELECT * FROM `$table_name` LIMIT $perpage OFFSET $page_num");


  • ادهم علام
    Posted on

    ادهم علام ادهم علام

    Reply Author

    تسلم ايدك ونتمنى لك التوفيق
    مشكور الك


  • Dude
    Posted on

    Dude Dude

    Reply Author

    Nice definatly the best one i have found so far but whats the best way to display less links, i only want to show like 3-5 links maximum and the lowest i can seem to get it with your script is 7 -9 and i dont have enough room.


  • Adam
    Posted on

    Adam Adam

    Reply Author

    Hey, this is a great tutorial! I’ve got it all working, but I want to sort my results by the date the data was submitted to the database. I’ve changed the query to SELECT * FROM dream ORDER BY `date_entered` DESC but it doesn’t seem to work, anybody know why?

    Any help would be greatly appreciated, thanks, Adam.


  • Tutorial City
    Posted on

    Tutorial City Tutorial City

    Reply Author

    It would be very cool if you had created a simple .htaccess to display pretty URLs
    Nice tutorial 😉


  • Dean Clatworthy
    Posted on

    Dean Clatworthy Dean Clatworthy

    Reply Author

    You should isolate pagination logic into it’s own class. This code is hard to reuse compared to something like:

    $pagenav = new pagenav($_REQUEST[‘p’], 10, $count[‘total’], ‘documents.php?do=overview’);

    Then the object will calculate the LIMIT values based on the parameters you pass in:

    LIMIT $pagenav->lower, $pagenav->upper

    Then of course you can render your pagenav using:

    $pagenav->render()

    I really should get around to publishing a few of these utility classes I’ve wrote. I hope it will encourage you to consider doing this for your example :)


  • thinsoldier
    Posted on

    thinsoldier thinsoldier

    Reply Author

    What if I don’t want to paginate “everything”?

    What if I only want the results of a users search using an advanced search form?

    What if that form page submits to this paginated Results page which then builds sql for the users desired query and paginates the results?

    When they click on the “next page” how is the sql given to the next page when the sql doesn’t exist hard coded into this results page?

    What if several sections of my site are like this and all use different tables?

    What if to address the issue of passing the dynamically generated user query from one page to the next I chose to switch to having the page number in a select in a form with hidden fields containing the users original choices so that they could be posted to the next page resulting in the exact same base sql being created for the next page? I’d have to make a lot of edits that aren’t directly related to the act of pagination in a region of code full of pagination related code.

    I think it would be better to separate the display of page number links (and any display logic involved) into a separate template-like file that gets included after the main pagination & query stuff happens.

    (My personal pagination _class_ is simultaneously MUCH worse AND MUCH MUCH MUCH better.)

    $sql = “SELECT * FROM tblcountry $dynamicWhereClause ORDER BY cTitle ASC”;

    $pgn8 = new pagination($sql, 20); // 20 items per page

    echo $pgn8->showingFromTo(); // Showing 121 – 135 of 1592 Results Found

    $page_result = $pgn8->findPageResult();

    echo $links = $pgn8->displayPagination(‘pgn8-.tpl’);
    // show clickable page numbers before result list using one of the non-default markup template files (maybe this one uses roman numerals?)

    while($row = mysql_fetch_assoc($page_result))
    { loop through and display rows data as list items or table rows etc }

    echo $links; // show page numbers after the results list again if you feel like it.


  • Davinder
    Posted on

    Davinder Davinder

    Reply Author

    You can easily do this in ASP.NET MVC!


  • Gijs
    Posted on

    Gijs Gijs

    Reply Author

    You can better use SQL_CALC_FOUND_ROWS so you dont have to create two querys that are doing the same.


  • Monkeytail
    Posted on

    Monkeytail Monkeytail

    Reply Author

    Nice! ( though I’am not a big fan of all the if-else nesting going on)
    Spice it up with a little bit more of code-commenting


  • Ben
    Posted on

    Ben Ben

    Reply Author

    Could you upload the data you used for the database? It would be really useful


  • raveren
    Posted on

    raveren raveren

    Reply Author

    PHP4? Why?


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Raveren, I have no idea what your referring to, there is nowhere in my article that refers to PHP4.


  • Limno
    Posted on

    Limno Limno

    Reply Author

    Excellent Post,

    Perfectly working…..Need this kinds of post to help us…

    Regards
    Limno.


  • Norris Jay
    Posted on

    Norris Jay Norris Jay

    Reply Author

    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Norris it’s based on exactly the same script which was originally written by the guys over at Stranger Studios


  • Dan Cunningha
    Posted on

    Dan Cunningha Dan Cunningha

    Reply Author

    Top man! Thanks for sharing.
    This is possibly one of the cleaner examples around on the internet to date.

    No doubt it will help a fair few.

    Cheers!
    Dan.