Networking, Programming and Graphics - Tutorials
ONLINEHOWTO.net Tutorials Category

Paging using PHP & MySQL with AJAX

Type: Code Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Level: Intermediate Networking, Programming and Graphics - Tutorials Networking, Programming and Graphics - Tutorials 
Networking, Programming and Graphics - Tutorials
Date: 2010-Feb-01
Networking, Programming and Graphics - Tutorials
Visited: 3490 times
Networking, Programming and Graphics - Tutorials
Rating: Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Published: Ivory Morhuld

Most users when works with large databases for websites with much more records in it and when want to list all results, experiencing problems how to display the data and how to keep small and nice looking web page with fast page load time.

Very elegant way to workaround with this is to display the limited result using SELECT * FROM `table` LIMIT $from, $how_much where:

$from - from which result to start listing
$how_much - how much results to list

And below the table with listed results to display paging navigation like this:

[1] 2 3 4 5

Next when user clicks on any button he can navigate in results by sending different values for $from parameter using GET or POST method. In our case this will be made with AJAX for prevent page loading and faster paging in the results.

In this tutorial I will show you exactly this - how to make Paged Result Query with AJAX using PHP & MySQL.

Now lets start with configuration of main parameters for data base connection and page result listing. This is our config.php file which we will include in several other files later:
<?php
// mysql database connection setup
$host='localhost';
$username='root';
$password='cP87-31^s0h';
$db_name='users';

// how many results to display in one page
$results_per_page=5;

// connect and select data base
$connect=mysql_connect($host$username$password);
$dbase=mysql_select_db($db_name);
?> 
Here is the complete code for MySql query for listing of default first page. Please note that this script uses AJAX function which makes GET request to the server to get only one page from all results.
<html>
<head>
<title>Paged Result Query with AJAX using PHP &amp; MySQL</title>
<script language="JavaScript" type="text/javascript">
function goto_page(page) {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }
    var url="ajax.php";
    url=url+"?page="+page;
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete") {
            document.getElementById('results').innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

function GetXmlHttpObject() {
    var xmlhttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlhttp=new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlhttp;
}
</script>
</head>
<body>
<div id="results">
<?php
// include config file
include("config.php");

$result=mysql_query("select * from `users`");
$all_result=mysql_num_rows($result);

// calculate total number of pages needed
$pages=ceil($all_result/$results_per_page);

$get_first_result=mysql_query("select * from `users` limit 0, $results_per_page");
echo 
"<table id=\"results\">";
// list first page results
while(list($id,$username,$full_name,$email,$password)=mysql_fetch_row($get_first_result)) {
    echo 
"<tr>\n
        <td>"
.$id."</td>\n
        <td>"
.$username."</td>\n
        <td>"
.$full_name."</td>\n
        <td>"
.$email."</td>\n
        <td>"
.$password."</td>\n
    </tr>\n"
;
}

// list page navgation ([1] 2 3 4 5)
    
echo "<tr>\n";
        echo 
"<td colspan=\"5\">\n";
$page=1;
while(
$pages) {
    if (
$page==1) {
        echo 
"<a href=\"javascript:goto_page(".$page.");\"><b>[".$page."]</b></a>&nbsp;&nbsp;&nbsp;\n";
    } else {
        echo 
"<a href=\"javascript:goto_page(".$page.");\">".$page."</a>&nbsp;&nbsp;&nbsp;\n";
    }
    
$pages--;
    
$page++;
}
        echo 
"</td>\n";
    echo 
"</tr>\n";
echo 
"</table>";
?>
</div>
</body>
</html>
Here is AJAX server side PHP file which catch GET request for wanted page (sent like url parameter), makes MySql query for this page and returns results only for this page. Like in our example you have to save this into file named ajax.php in the same folder:
<?php
// include config file
include("config.php");

if (
is_numeric($_GET['page'])) {
    
// calculate total number of pages needed
    
$result=mysql_query("select * from `users`");
    
$all_result=mysql_num_rows($result);
    
$pages=ceil($all_result/$results_per_page);

    echo 
"<table width=\"100%\">";

    
// calculate starting position for listing the results
    
$offset=$results_per_page*($_GET['page']-1);

    
$get_current_result=mysql_query("select * from `users` limit $offset, $results_per_page");
    
// list results for current page
    
while(list($id,$username,$full_name,$email,$password)=mysql_fetch_row($get_current_result)) {
        echo 
"<tr>\n
            <td>"
.$id."</td>\n
            <td>"
.$username."</td>\n
            <td>"
.$full_name."</td>\n
            <td>"
.$email."</td>\n
            <td>"
.$password."</td>\n
        </tr>\n"
;
    }

    
// list page navgation ([1] 2 3 4 5)
        
echo "<tr>\n";
            echo 
"<td colspan=\"5\">\n";
    
$page=1;
    while(
$pages) {
        if (
$page==$_GET['page']) {
            echo 
"<a href=\"javascript:goto_page(".$page.");\"><b>[".$page."]</b></a>&nbsp;&nbsp;&nbsp;\n";
        } else {
            echo 
"<a href=\"javascript:goto_page(".$page.");\">".$page."</a>&nbsp;&nbsp;&nbsp;\n";
        }
        
$pages--;
        
$page++;
    }
            echo 
"</td>\n";
    echo 
"</tr>\n";
    echo 
"</table>";
}
?>
Now let see how all of this got work:
1 johnb John Bravo johnb@onlinehowto.net jkhg345
2 alxes Alex Smith alexsm@onlinehowto.net 235623cvbn
3 peterk Peter Klever pkev@onlinehowto.net wrwt6798
4 ivang Ivan Grovy ivan.gr@onlinehowto.net 6784dfgh
5 smithw Smith Western wsmith@onlinehowto.net 2724657xcsd
[1]    2    3    4    5   
Rate this tutorial:                    
Post Comment

    • ( guptavipin1984 [ at ] gmail . com ),

      posted on 2010-Feb-19 | 04:08:38 AM
      The code is good. But i m not getting properly. Can u send me code in zip file. So can use. Plz

    • posted on 2010-Feb-19 | 05:30:02 AM
      Hi Vipin,

      1. Copy & Paste the first code in file with name - config.php
      2. Copy & Paste the second code in file with name - index.php
      3. Copy & Paste the third code in file with name - ajax.php
      4. Set correct parameters for:
      $host=
      $username=
      $password=
      $db_name=
      in config.php file.
      5. Fill 5-column database with correct data and you are ready.

      Note: All files have to be saved in document root of your web server.
    • ( minhkhoa [ at ] hotmail . com ),

      posted on 2010-May-25 | 08:16:31 PM
      this work on Firefox but not on IE event on your web page. I got "Unknow runtime error" on IE line 340 on your web page. This same problem occur when I test the script on my server. Please advise.

    • posted on 2010-May-27 | 04:22:26 AM
      Problem was fixed. (IE cannot operate with some DOM elements with .innerHTML function)
    • ( alexander . murad [ at ] gmail . com ),

      posted on 2010-Jun-10 | 12:09:48 AM
      Hello,

      I have try using my database, but when i click to page 2 the navigation is gone. Either FF and IE is the same. Do i miss something.
    • ( albert [ at ] gmail . com ),

      posted on 2010-Jun-24 | 11:23:22 PM
      I got everything to work however, on the ajax.php page, or clicking on page 3 or 4, i don't see the pagination any longer with firefox or IE. Please help
    • ( jmiguy [ at ] hotmail . com ),

      posted on 2010-Jul-24 | 12:32:09 PM
      Your script works great, thanks for posting it. The problem I'm having is when trying to use your script with my existing filtering script. I want to display a page listing article titles with brief description, post date, etc.

      I want to use your paging script but would also like to use dropdown lists to be able to sort by newest, A-Z, etc. I also want a second dropdown to sort by article category.

      I can get paging and sorting to work perfectly when separate but I cannot seem to merge them together. Do you have a code example you could provide that has both paging and sorting?

      Thanks,

      Jeff

    • posted on 2010-Jul-26 | 02:59:48 AM
      Alexander & Albert,

      Thanks for the note. Problem was fixed.
    • ( jmiguy [ at ] hotmail . com ),

      posted on 2010-Jul-29 | 02:13:40 PM
      Do you have a tutorial or code to sort the paginated results? Such as by using drop down box filters?
Need a specific tutorial? Do not hesitate and submit a request!
Your e-mail: