January 19, 2024 5:02 am

How to create pagination in PHP and MySQL with AJAX

I have wrote an article on pagination with a simple class and many users like it and download it so now i have decided to write its and updated version with AJAX. In this article i am going to explain you how to create pagination in PHP & MySQL with AJAX for your websites. Pagination is a very important part in your websites reporting and this article will help you to create it very very simple.

ajax-pagination

[wpdm_file id=32]DEMO

Also Read: How to create Advance Pagination in PHP & MySQL with jQuery

Database design and table:

database name => phpgang
table name => pagination
column names => id, post, postlink

db.sql

Database file run in your mysql to create database and add data in table.

create database `phpgang`;
use `phpgang`;
CREATE TABLE `pagination` (
  `id` int(11) NOT NULL auto_increment,
  `post` varchar(250) NOT NULL,
  `postlink` varchar(250) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=48 DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;

INSERT INTO `pagination` VALUES (1, 'How to Resize text using jQuery', 'https://www.phpgang.com/?p=312');
INSERT INTO `pagination` VALUES (2, 'How to Integrate live search in PHP and MySQL with jQuery', 'https://www.phpgang.com/?p=309');
INSERT INTO `pagination` VALUES (3, 'How to implement jquery Timeago with php', 'https://www.phpgang.com/?p=290');
INSERT INTO `pagination` VALUES (4, 'How to Mask an input box in jQuery', 'https://www.phpgang.com/?p=304');
INSERT INTO `pagination` VALUES (5, 'How to block Inappropriate content with javascript validation', 'https://www.phpgang.com/?p=301');
INSERT INTO `pagination` VALUES (6, 'How to Crop Image with jQuery and PHP', 'https://www.phpgang.com/?p=298');
INSERT INTO `pagination` VALUES (7, 'How to Integrate jQuery Scroll Paging with PHP', 'https://www.phpgang.com/?p=294');
INSERT INTO `pagination` VALUES (8, 'Bug Reporting with Windows Program Steps Recorder (PSR)', 'https://www.phpgang.com/?p=291');
INSERT INTO `pagination` VALUES (9, 'How to Configure Google Cloud API in PHP', 'https://www.phpgang.com/?p=288');
INSERT INTO `pagination` VALUES (10, 'How to convert text to MP3 Voice', 'https://www.phpgang.com/?p=284');

db.php

Database configuration file edit database name, user and password as per your configuration.

<?php
    $connection = mysql_connect('localhost','phpgang','********') or die(mysql_error());
    $database = mysql_select_db('phpgang') or die(mysql_error());
?>

style.css

Use Css for style.

<style type="text/css">
ul.tsc_pagination { margin:4px 0; padding:0px; height:100%; overflow:hidden; font:12px \'Tahoma\'; list-style-type:none; }
ul.tsc_pagination li { float:left; margin:0px; padding:0px; margin-left:5px; }
ul.tsc_pagination li:first-child { margin-left:0px; }
ul.tsc_pagination li a { color:black; display:block; text-decoration:none; padding:7px 10px 7px 10px; }
ul.tsc_pagination li a img { border:none; }
ul.tsc_paginationC li a { color:#707070; background:#FFFFFF; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; border:solid 1px #DCDCDC; padding:6px 9px 6px 9px; }
ul.tsc_paginationC li { padding-bottom:1px; }
ul.tsc_paginationC li a:hover,
ul.tsc_paginationC li a.current { color:#FFFFFF; box-shadow:0px 1px #EDEDED; -moz-box-shadow:0px 1px #EDEDED; -webkit-box-shadow:0px 1px #EDEDED; }
ul.tsc_paginationC01 li a:hover,
ul.tsc_paginationC01 li a.current { color:#893A00; text-shadow:0px 1px #FFEF42; border-color:#FFA200; background:#FFC800; background:-moz-linear-gradient(top, #FFFFFF 1px, #FFEA01 1px, #FFC800); background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #FFFFFF), color-stop(0.02, #FFEA01), color-stop(1, #FFC800)); }
ul.tsc_paginationC li a.In-active {
   pointer-events: none;
   cursor: default;
}
</style>

function.php

Pagination Logic function Include in your file.

<?php
define('PAGE_PER_NO',8); // number of results per page.
function getPagination($count){
      $paginationCount= floor($count / PAGE_PER_NO);
      $paginationModCount= $count % PAGE_PER_NO;
      if(!empty($paginationModCount)){
               $paginationCount++;
      }
      return $paginationCount;
}
?>

index.php

Index file contain pages logic.

include_once('db.php');
include_once('function.php');
$query="select id from pagination order by id desc";
$res=mysql_query($query);
$count=mysql_num_rows($res);
if($count > 0){
      $paginationCount=getPagination($count);
}

$content ='<div id="pageData"></div>';
if($count > 0){

$content .='<ul class="tsc_pagination tsc_paginationC tsc_paginationC01">
    <li class="first link" id="first">
        <a  href="javascript:void(0)" onclick="changePagination(\'0\',\'first\')">F i r s t</a>
    </li>';
    for($i=0;$i<$paginationCount;$i++){

        $content .='<li id="'.$i.'_no" class="link">
          <a  href="javascript:void(0)" onclick="changePagination(\''.$i.'\',\''.$i.'_no\')">
              '.($i+1).'
          </a>
    </li>';
    }

    $content .='<li class="last link" id="last">
         <a href="javascript:void(0)" onclick="changePagination(\''.($paginationCount-1).'\',\'last\')">L a s t</a>
    </li>
    <li class="flash"></li>
</ul>';
}

AJAX Code

<script type="text/javascript">
function changePagination(pageId,liId){
     $(".flash").show();
     $(".flash").fadeIn(400).html
                ('Loading <img src="image/ajax-loading.gif" />');
     var dataString = 'pageId='+ pageId;
     $.ajax({
           type: "POST",
           url: "loadData.php",
           data: dataString,
           cache: false,
           success: function(result){
                 $(".flash").hide();
                 $(".link a").removeClass("In-active current") ;
                 $("#"+liId+" a").addClass( "In-active current" );
                 $("#pageData").html(result);
           }
      });
}
</script>

loadData.php

This file load data from database on auto load and onclick events.

<?php
include_once('db.php');
include_once('function.php');

if(isset($_POST['pageId']) && !empty($_POST['pageId'])){
   $id=$_POST['pageId'];
}else{
   $id='0';
}
$pageLimit=PAGE_PER_NO*$id;
$query="select post,postlink from pagination order by id desc
limit $pageLimit,".PAGE_PER_NO;
$res=mysql_query($query);
$count=mysql_num_rows($res);
$HTML='';
if($count > 0){
while($row=mysql_fetch_array($res)){
   $post=$row['post'];
   $link=$row['postlink'];
   $HTML.='<div>';
   $HTML.='<a href="'.$link.'" target="blank">'.$post.'</a>';
   $HTML.='</div><br/>';
}
}else{
    $HTML='No Data Found';
}
echo $HTML;
?>

Please Download the code and use this script feel free to comment if face any issue in it we love to reply on your comments. 🙂

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

47 responses to “How to create pagination in PHP and MySQL with AJAX”

  1. atul says:

    realy nice working. gr8

  2. farmanullah memon says:

    good job

  3. Ruby James says:

    Nice Article sir

  4. Susang says:

    i can’t get access to the db and it comes with “Access denied for user ”@’localhost’ to database ‘phpgang'”. have set a password to the database

  5. Luca Pandolfo says:

    If I have a lot of pages…can I hide with “…” like the image of this article? Can you explain me how I can do this? Thx

  6. Mahmudur Rahman says:

    Why you need the downloader to be a subscriber ?

  7. Amr Dam says:

    how i can download demo

  8. dskanth says:

    Thanks for this simple yet powerful explanation of using jquery ajax with php 🙂

  9. Army says:

    Thank you I want to download source code

  10. Army says:

    How i can download code ?

  11. Danish says:

    Hi.. My question is same as Luca Pandolfo. I want “…” between numbers as shown in tutorial image. i try to edit function.php but don’t get it. how to get this thing?

  12. Unais Ellias says:

    How i can download code ?

  13. Bakhtiyor says:

    I subscribed, but I can`t download. Error: “Sorry no email found subscribe below”

  14. Mark says:

    In the demo I see 24 links and that is all. So where is the prev nex button?

  15. amin rohmatullah says:

    Thanks for this great code. By the way, I have one table with two columns, each column has its own content, and I want both of them paginated independently, Where and how should i modify the code ?

  16. Penelope says:

    I subscribed, confirmed, but cannot download still. It says that there is no E-Mail address under that name.

  17. rajendher says:

    dear admin,
    which displays all the page numbers. but we need first 1,2,3 …..8,9,10 last like . what should we do now.
    please reply……… appriciated more ……….

    • huzoorbux says:

      Use our Latest Tutorial on Pagination with ……. How to create Advance Pagination in PHP & MySQL with jQuery Latest Article.

      • rajendher says:

        yeah i have seen just now. but i am getting following error message in “loadData.php” why ?
        The page cannot be displayed because an internal server error has occurred.
        there is no error in database connection but not getting please help sir…………

  18. orhanturk says:

    An article has been very successful in

  19. Oeurn Sophearith says:

    Dear phpgang!
    Why i can’t do. it is no result at all.
    and when i click download this script it is error and can not download it.
    please….. send it for me please….

  20. hossein says:

    this article is very good…
    please send for me tanks

  21. Ashiq says:

    how to display all months from create date to end date in archives…
    ex: august 2014(2)
    july 2014(0)
    march 2014(2)

  22. Ankur says:

    great tutorial,was searching for the same from a long time.

  23. สุกนกานต์ says:

    thank you for script

  24. Jerry says:

    I have no idea what I am doing wrong, but I could not get this to work. The best it would do is display the pagination but no data from the database. It gave no errors.

  25. Jerry says:

    I have no idea what I am doing wrong, but I could not get this to work. The best it would do is display the pagination but no data from the database. It gave no errors.

  26. Tharun says:

    How to do column level search using ajax.. can u please make on tutorial ?..

  27. Atul pradhan says:

    actually m getting problem that, its displaying first page but when i click second page showing nothing and repeating my div blank on the same page. and not going back too.

  28. Paritus Jaimun says:

    thanks

  29. Shuttheup Eiei says:

    Thank you

  30. ปอ ยังซิง says:

    thanks

Leave a Reply

Your email address will not be published. Required fields are marked *