My Programming Tutorials

My Programming Tutorials

How to create Pagination with PHP and MySql

Last updated on by , 218 comments

In this tutorial, we are going to create pagination with PHP and MySql. It is probably possible that your SQL SELECT query may return results into thousand and millions of records. And it is obviously not a good idea to display all those results on a single page. So we can split this result into multiple pages.

What is Pagination?

Paging means displaying all your fetched results in multiple pages instead of showing them all on one page. It makes that page so long and would take so much time to load.

How to create Pagination with PHP and MySql

MySQL’s LIMIT clause helps us to create a pagination feature. It uses two arguments First argument as OFFSET and the second argument the number of records which will be returned from the database.

You can find ajax version for this tutorial in my other article ajax pagination here.

Follow these simple steps to create pagination in PHP – 

1. Get the current page number

This code will get the current page number with the help of $_GET Array. Note that if it is not present it will set the default page number to 1.


if (isset($_GET['pageno'])) {
    $pageno = $_GET['pageno'];
} else {
    $pageno = 1;
}

 

2. The formula for php pagination

You can always manage the number of records to be displayed in a page by changing the value of $no_of_records_per_page variable.


$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page; 

 

3. Get the number of total number of pages


$total_pages_sql = "SELECT COUNT(*) FROM table";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);

 

4. Constructing the SQL Query for pagination


$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page"; 

 

5. Pagination buttons

These Buttons are served to users as Next Page & Previous Page, so that they can easily navigate through you pages. Here I am using bootstrap’s pagination button, you can use your own buttons if you want.


<ul class="pagination">
    <li><a href="?pageno=1">First</a></li>
    <li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
        <a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
    </li>
    <li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
        <a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
    </li>
    <li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
</ul>

 

6. Let’s assemble all the codes in one page


<html>
<head>
    <title>Pagination</title>
    <!-- Bootstrap CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <?php

        if (isset($_GET['pageno'])) {
            $pageno = $_GET['pageno'];
        } else {
            $pageno = 1;
        }
        $no_of_records_per_page = 10;
        $offset = ($pageno-1) * $no_of_records_per_page;

        $conn=mysqli_connect("localhost","my_user","my_password","my_db");
        // Check connection
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            die();
        }

        $total_pages_sql = "SELECT COUNT(*) FROM table";
        $result = mysqli_query($conn,$total_pages_sql);
        $total_rows = mysqli_fetch_array($result)[0];
        $total_pages = ceil($total_rows / $no_of_records_per_page);

        $sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_array($res_data)){
            //here goes the data
        }
        mysqli_close($conn);
    ?>
    <ul class="pagination">
        <li><a href="?pageno=1">First</a></li>
        <li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
            <a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
        </li>
        <li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
            <a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
        </li>
        <li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
    </ul>
</body>
</html>

That’s all!

If you find this article helpful, don’t forget to share it with your friends. And stay updated with us by subscribing our blog.

Author Info

Paritosh Pandey

He loves Technology

Advertisement

218 responses to “How to create Pagination with PHP and MySql”

  1. Rohit says:

    very nice way to describe things…keep doing the good work

  2. Jass says:

    hi Paritosh
    dude you doing the best job for the beginners who start a career in web development

  3. Buy Contact Lenses says:

    Hey keep posting such good and meaningful articles.

  4. Emilio B says:

    When I use a submit form with post and the query with select * from xxx Like “search”, when I click to another page the post variable is gone. How to fix this?

    • Paritosh Pandey says:

      you just have to pass your searched variable in pagination buttons (in URI GET param),
      append this in pagination buttons &q=$searchedVariable

      • Diogo says:

        So i’m trying to do what you said and its not going well.
        what is exactly the searched variable is it the $query=select * from xxx Like “search”? or something else?

      • Mike says:

        Hello! I’m to stupid to check this 🙂

        where should i add this?

        // Check connection
        if (mysqli_connect_errno()){
        echo “Failed to connect to MySQL: ” . mysqli_connect_error();
        die();
        }

        $total_pages_sql = “SELECT COUNT(*) FROM customers”;
        $result = mysqli_query($conn,$total_pages_sql);
        $total_rows = mysqli_fetch_array($result)[0];
        $total_pages = ceil($total_rows / $no_of_records_per_page);

        $sql = “SELECT * FROM customers LIMIT $offset, $no_of_records_per_page”;
        $search = isset($_POST[‘search’]) ? $_POST[‘search’] : ”;
        $sql = “SELECT * FROM customers WHERE NAME1 LIKE ‘%$search%’ OR STREET LIKE ‘%$search%’ LIMIT $offset, $no_of_records_per_page”;
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_array($res_data)){
        echo “”;
        echo “” . $row[‘ID’] . “”;
        echo “” . $row[‘NAME’] . “”;
        echo “” . $row[‘STREET’] . “”;
        echo “”;
        echo ““;
        echo ““;
        echo ““;
        echo “”;

        echo “”;
        }
        echo “”;

        mysqli_close($conn);
        ?>

        First
        <li class="<?php if($pageno “>
        <a href="<?php if($pageno “>Prev

        <li class="= $total_pages){ echo ‘disabled’; } ?>”>
        <a href="= $total_pages){ echo ‘#’; } else { echo “?pageno=”.($pageno + 1); } ?>”>Next

        <a href="?pageno=”>Last

    • Emma says:

      Me too facing this challenge. Can you help about this?

  5. ntambi says:

    am getting an error of undefined variable
    pegno of get array

  6. Great Tutorial! This PHP pagination tutorial have all the options. But I think it would be better if you add an option to change the total number of results. What do you think about it?

    • Paritosh Pandey says:

      Hello @Souradeep,

      Thank you for such valuable comments. And yeah its a good idea, I definitely gonna implement your suggestion.

  7. edrine says:

    nice tutorial but i have some problem i am gettng error
    undefined pageno

    • Paritosh Pandey says:

      Hello @Edrine,

      please make sure to place below code at the top of page

      
      if (isset($_GET['pageno'])) {
          $pageno = $_GET['pageno'];
      } else {
          $pageno = 1;
      }
      
      
  8. ali says:

    Hey,

    Great tutorial mate.

    But I’ve got some GET variables in the URL, which are lost when I press the NEXT or any other button. It just edits the URL to “?pageno=2”.

    It’d great if you fixed that. Thanks!

  9. ali says:

    Hey Paritosh,

    Thanks for your reply. How do I do that? Any pointer?

    Thanks again!

    • Paritosh Pandey says:

      suppose you have 2 get params (type & status) in your url

      then pagination code would be

      
      <ul class="pagination">
          <li><a href="?type=test&status=test&pageno=1">First</a></li>
          <li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
              <a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?type=test&status=test&pageno=".($pageno - 1); } ?>">Prev</a>
          </li>
          <li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
              <a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?type=test&status=test&pageno=".($pageno + 1); } ?>">Next</a>
          </li>
          <li><a href="?type=test&status=test&pageno=<?php echo $total_pages; ?>">Last</a></li>
      </ul>
      
      
  10. Hamza jawaid says:

    Bro, you did a great job..
    Really appreciated,
    Thanks

  11. Mudiaga Obriki says:

    Good day. The paginator is displaying at the bottom but when I click next, it returns empty results.

    • Paritosh Pandey says:

      could it be possible to provide a demo link for your paginator, it helps me to understand better.

  12. Ben says:

    Am getting an error that a non numeric value was encountered on the line holding the next page code am new to php help

  13. Mubarak Auwal says:

    Nice tutorial overall, how do I re write the URL in to something like this
    https://www.myprogrammingtutorials.com/page/2
    ? Any tip will be of great help

    • Paritosh Pandey says:

      you can use RewriteRule ^(.*)$ index.php?params=$1 [NC] in your .htaccess file, so that your old url
      http://url.com/index.php?params=value
      be like
      http://url.com/params/value

      • Ebrinix says:

        Hi Paritosh, I am trying to echo $result but I get this message: Resource id #17 when I do. Please what is the cause?

  14. maliksanwal says:

    good posting good website

  15. Scarlet says:

    Aaaaaa, thanks sir!! just now i got it xD

  16. Ebrinix says:

    Hi, in the process of writing the code I try to echo $result before I proceed but got this message: Resource id #17. Please how do i sort it out?

    • Paritosh Pandey says:

      please let us see the whole error if possible, it’ll help me to figure the problem out.

      • Ebrinix says:

        I didn’t get an error, I only got the message: Resource id #17. please I need help, I’ve been battling with this for day…

    • Paritosh Pandey says:

      after echo the $result variable you should get
      Object of mysqli_result couldn’t be converted to string
      error

  17. roan says:

    dude when i clicked on next, its always launch me to other page, how can i fix this? thanks

  18. cmarisa says:

    Hi,

    how do I get page numbers to show?

    • Paritosh Pandey says:

      you could use

      
      if (isset($_GET['pageno'])) {
          $pageno = $_GET['pageno'];
      } else {
          $pageno = 1;
      }
      
  19. Faisal Aziz says:

    Very Informative.
    Make a tutorial on nested comments in php

    • Paritosh Pandey says:

      Thank you for appreciating @Faisal
      sure I will post a tutorial on nested comments, meanwhile, you can use
      “https://www.myprogrammingtutorials.com/multi-level-nested-category-system-codeigniter-mysql.html” concept for your nested comments.

  20. Gerald says:

    Thank you for this tutorial, I encountered some problem
    my url is already ?pageno=2 but the table is still at page 1.

  21. Ajemuta Isaac says:

    not displaying data
    i don’t know if i should add the field of table
    Thank

  22. Sahan Nimesh says:

    Thanks man. It was really helpful. Thank you very much

  23. rajendra kandel says:

    i dont understand the pageno meanining in the first isset line is it a functio or what and please describe about $offset = ($pageno-1) * $no_of_records_per_page;

    • Paritosh Pandey says:

      The OFFSET clause skips the offset rows before beginning to return the rows. Maybe this image can help you understand better

  24. Ayesha says:

    while($row = mysqli_fetch_array($res_data)){
    //here goes the data
    }

    What data goes in while loop?????

    • Paritosh Pandey says:

      your actual data what you’re paginating at, it could be in <table> or in any element you want

  25. oge says:

    Good Job, really appreciate the script…been having a hard time implementing serial numbering that increments on every page

  26. Khizar says:

    The Code is working great

    any possibility to put the pagination buttons on top of the table ?

    when i do, they don’t function

  27. Ehtasham says:

    it’s really helpful thanks a lot.

  28. Amna says:

    i want to know how to show the result of search query using pagination

  29. Imran says:

    Sir,
    THANKS A LOT
    Very good work
    thanks

  30. Arjan says:

    Hey,
    I am using exactly the same code as yours, but not getting the desired result.
    I am not sure how to modify the href according to my web page. Can you please check my code and see if you can help me modify it and make it work?

  31. Hayk says:

    Thank you

    • Paritosh Pandey says:

      You should use AJAX pagination here, loading both views (List & Grid) is not a good practice, let me show you pointwise flow

      – serve view buttons (List & Grid) initially and make one default view
      – put “Next Button” downside
      – when a user clicks on “Next Button”, find his/her selected view (List & Grid) and make an AJAX request along with the selected view value
      – according to the view value, you can return its relevant html codes.
      – at last append response into the final container

      here is a good tutorial about ajax pagination

  32. rajesh says:

    Sir,
    THANKS A LOT
    Very good work
    thanks

  33. Bloserda says:

    This was really simple, great tutorial.
    But, why my page not show the number?
    Just :
    FirstPrevNextLast

    Thanks before.

  34. bloserda says:

    I try to use with nested loop, but iam stuck, could you help me?
    This is my query :

    query($query);
    $total_records = $result->num_rows;
    while($row = $result->fetch_array()) {
    $datarows[] = $row;
    }

    $num_cols = 3;
    $num_rows = ceil($total_records / $num_cols);
    $num = 0;
    echo “\n”;
    // next the loop for the table rows
    for ($rows = 0; $rows < $num_rows; $rows++) { echo "\n”; // this is the loop for the table columns for ($cols = 0; $cols < $num_cols; $cols++) { if ($num < $total_records) { // first create variables with the values of the current record $1 = $datarows[$num]['1']; $2 = $datarows[$num]['2']; $3 = $datarows[$num]['3']; echo " “.$1.” – “.$2.” – “.$3.” \n”; } else { // show an empty cell echo ” \n”; } $num++; } echo “\n”; } echo “\n”; ?>

  35. Stefan says:

    Nice tutorial but I believe your pagination example can be improved by also disabling the First and Last pagination buttons if you are currently on one of those pages.
    This is easily done so I won’t insult you by posting the code here! 🙂

  36. Ben says:

    How do I display/get the numbers between 0-10 instead of displaying prev and next button?

  37. Khamad Ali says:

    Thanks it’s helpfull. Nice blog 🙂

  38. Rémi Corso says:

    Hello and thx for this amazing tutoriel,

    I have a problem with this system, might be from my own code, could you help me?

    The pagination’s buttons working good, but the list limit isnt working.

    Could you help me in private mb?

    Thx a lot and nice job man, that’s amazing.

  39. Pritam Raghav says:

    i want to show some number of pages as well

  40. Abu bakar says:

    hi there i use this code for my listing page but i got error which icludes this message…

    Message: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

  41. ali says:

    hello
    i use your code for my search page but i have 2 error’s include this message :-

    mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in ..
    mysqli_query() expects parameter 1 to be mysqli, object given in …

    please help me , and thank you .

  42. ardrkn says:

    I’m new in PHP. And this article is so much helpfull people like me from beginning class. Thank you so much my firend! You did wonderfull job!

  43. Finntown says:

    Always the first line on the page is missing?
    $no_of_records_per_page = 5; and there is 14 rows total.
    The first page is 2…5
    The next page is 7…10
    The last page is 12…14.

  44. mauricio says:

    Excellent tutorial, shown from beginning to end, the way it should be.

  45. this is what I was looking for.
    thank you for your hard working.

  46. Basir Payenda says:

    Thank you so much, this solved my problem?
    Two questions?

    How do I make pagination for image galleries?
    How do I give a dynamic background color for active elements of pagination?
    Thank you

    • Paritosh Pandey says:

      you could use $total_pages in for loop

      
      for($i=1; $i<=$total_pages; $i++){
      
          if($pageno == $i){
              echo "selected";
          }
      
      }

      you could use above strategy in your pagination buttons

  47. Xwiit says:

    Thanks so much, this really helped me. I have searched all around for pagination like this, I really appreciate.

  48. Amjad says:

    Thanks, You are a Genius. God bless you!

  49. So far, I agree with you on much of the info you have written here. I will have to think some on it, but overall this is a wonderful article.

  50. Mae says:

    Thank you so much for sharing this pagination, very clear and easy to understand.
    God bless you, brother!

  51. Fahad Ahmed says:

    I paste that code in blog page in my blog page there are 3 content Image Title and Text but i pasted that code and change the number of page record means i want only 3 blog per page and go to next page but that code not work please reply my question as soon as fast

  52. C Vasanth says:

    That was useful code that I was looking for. I have added another column to the table to give it an edit capability with Edit and it works fine with an edit screen and n is dynamically generated.

    Thank you Paritosh ji for sharing this code which saved me a lot of time.

  53. Michael says:

    mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in line 52 where i have this code

    while($row = mysqli_fetch_array($query))
    {
    print_r($row);
    }

    Can you help me please?

  54. Laurentiu says:

    thank you this helped me alot

  55. Laurentiu says:

    while($row = mysqli_fetch_array($query))
    {
    $obj[] = $row;
    }
    foreach ($obj as $user){
    echo ”.$user[“username”].”;
    }

  56. Marc says:

    Tutoriel Simple et efficace, l’essentiel pour avoir une base solide. Puis chercher à l’améliorer. Merci pour cette aide, e me noyait dans les tutoriaux tellement nombreux sur ce sujet.
    (google translation)
    Tutorial Simple and effective, the essential to have a solid foundation. Then try to improve it. Thank you for this help, I was drowning in so many tutorials on this topic.
    Best reguards
    Marc

  57. Jick says:

    Great tutorial.
    How to show all pages instead of First,Previous,Next and Last?
    Example: I have 100 data to display which I would limit it to 10 per pages.
    I want to direct click on page 8 instead of keep clicking on Next button.
    Any guidelines? Thanks

  58. great tutorial, very usefull and solve my problem

  59. JS says:

    Thank you very much for this. Not only was the code useful but the step-by-step made it very easy to adapt

  60. Diego Torres says:

    Perfect!! just what I needed, Simple and easy

  61. Abbass Sharara says:

    Thank you very much I was searching for the sql query I was lost in it and you really helped me.

    Thank You So Much Again!!

  62. Sneha Biswas says:

    I understood the logic

  63. Roland says:

    Bless you! blended well with my script

  64. A good tutorial for learning. Thanks

  65. baba says:

    Thanks alot. Using your insturction i could simply insert the pagination to my data.
    I have another question:
    There are only First, Previous, Next and Last buttons.
    Is it possible to add the nummber buttons for pages besid these buttons. As the “pagination” of Google?

  66. Supriya says:

    good Tutorial for learning thanks

  67. karim says:

    love u man thank u very much for this tuto .

  68. Ajo says:

    I am getting an error i like this,
    mysql_fetch_array() expects parameter 1 to be resource, boolean given in…..
    I can’t use mysqli,because,in my project am using the earlier version.
    Here is my code:

    $link = mysql_connect($Host, $User, $Password) or die(‘Could not connect: ‘ . mysql_error());
    mysql_select_db($DBName) or die(‘Could not select database’);

    $total_pages_sql=”SELECT * from table”;
    $result = mysql_query($total_pages_sql);
    $total_rows = mysql_fetch_array($result,MYSQLI_NUM)[0];
    $total_pages = ceil($total_rows / $no_of_records_per_page);

  69. mahendra says:

    sir i have created a blog page. and it is working properly but 1 and 2 page post properly show . but when i click next page(3) it is showing blank and other page (like 4,5,6….) also.. i can not find where is my error.please help me why it can not show after 2 page..

  70. Sumith says:

    Thank for your post, but my dream viewer said has error in ” $total_rows = mysqli_fetch_array($result)[0];” how can i solve please….

  71. Vishal Rana says:

    Nice tutorial. I got many references.

  72. Amit Rajput says:

    Superb Work Man!

  73. Andy says:

    Great Tutorial have included it with some minor modification so it displays 100% for what i need only issue i have is i have records that shows a visit count per member and when i adjust the $sql to

    $sql = “SELECT * FROM dxd_members LIMIT $offset, $no_of_records_per_page ORDER BY visits DESC”;

    so that is lists members by the visit count highest to lowest i am getting this error

    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in C:\Server\data\htdocs\dxdadmin\inc\member_visits.inc.php on line 61

    How can i fix this so that i can have it shows my members by the number of visits highest to lowest.

    Thanks

    • Paritosh Pandey says:

      please post the codes atleast from line no 60 – 65 of your file “member_visits.inc.php” in order to identify the problem.

  74. Shrenik says:

    Thanks For This Post.

  75. konain says:

    very nice i appriciate you thank you so much bro

  76. Renly says:

    Hello Paritosh, Nice tutorial. I am trying to implement this code in my project but whenever i click next page it returns empty. Cn you please take a look at my code and help me out.

    https://imgur.com/a/XmDk1L7

    • Paritosh Pandey says:

      as I can see here (at line no 100), you’re using $result variable instead of $result1.

      
      while($row = mysqli_fetch_array($result))
      
      • Renly says:

        There are two variables result, result1. i am doing this for result.

        • Paritosh Pandey says:

          though it is hard to diagnose like this, my suggestion would be

          #try diagnosing step by step, like whether or not any queries are getting executed and returning any data?

          #if it returns, move ahead to next query.

          #see error logs

          #use exception.

  77. sammy says:

    it worked amazing for me bah how can i ignore my first 5 posts before i limit the number of post to show
    like this

    $query = “SELECT * FROM article a INNER JOIN
    article_category ac
    WHERE a.article_cat_id=ac.article_cat_id
    AND ac.article_category=’General News’
    ORDER BY posted_time DESC
    LIMIT 5, 4”;

    here the code will ignore the first 5 and limit to show 4
    how do i do that to yours codes
    thank u

    • Paritosh Pandey says:

      you need to do some hard code here, first check whether it is first page or not, if it is a first page the set the $offset to 5(hardcoded). like so

      
      if($pageno == 1){
          $offset = 5;
      }
      
  78. ibrahim says:

    First of all, thank you. I have 10 yields. I want to divide it into 2 pages. It creates 2 pages. There is no problem here. It shows the same 10 data on 2 pages.

    • Paritosh Pandey says:

      Hello ibrahim,

      it is hard to find the problem this way, if it could be possible to share your codes, please do so.

  79. Jimi says:

    Really helpful.

    It worked perfectly for me!

    Thanks

  80. It’s very helpful dear for my website. Thanks and keep it up.

  81. Nasibullo says:

    Hello , the code is not full , where is sql? I cant use it in practise.
    you just put some buttons , thats all? it gives error and I dont see anything except of buttons, why you did it , why you confuse all people, why its so bad.
    I cant understand what I NEED myself here, why you didnt full it with pages and
    with html and sql codes. You just wrote some php code with that is impossible to do something

  82. Metro Lagu says:

    It’s very helpful dear for my website. Thanks and keep it up.

  83. peter says:

    hello, please itried implementing it on a search filter but didnt work… please help…

  84. is it possible to do it in simple way

  85. Nebojsa says:

    Hey,
    I’m using this code, but I have a problem loading on diffrent pages.

    In my index page I’m using this code

    So in my main page it’s working fine where I listed some stuff, but in admin page where I added button “Edit” it’s only showing on first page, and when I’m loading pageno=2, it’s showing me the result from my main page, without button.
    It works fine if I put it in main page.

    Please Help!

  86. Hakim says:

    I need pagination with bootstrap 3 columns. can you help me, please?

  87. ritwik says:

    bhai kasam se dil se sukriya yara kal se itne plugins laga kr dekh chuka hu itni sari codings dekhi but bhai bht light tarike se apne bht accha explain karte huye mast sikha diya no need of any plugin now thnks a lot bhai

  88. Dave Byrne says:

    You can improve this by printing the previous, current and next page numbers in numeric digit form in the middle of the first/prev/next/last buttons.

    I made the following code:

    1){echo ($pageno – 1).” “;} echo ““.$pageno.” “; if($pageno

  89. Anand singh says:

    Your method of describing is awesome, thanks for sharing with us.

  90. parth says:

    This Code is Codeigniter Api Create in pagination in error is every to page number change in show last recode this error how can sold

    ==============================================================================
    public function product_data($category_id = null,$subcategory_id = null,$user_id = null,$page = 1)
    {
    if (!is_null($this->db))
    {
    /*$row = 10;
    $row_pre = ($page * $row) – $row;*/

    $this->db->select(‘*’);
    $this->db->from(“products”);
    if(!is_null($category_id) || !is_null($subcategory_id)){
    $this->db->where(‘category_id’, $category_id);
    $this->db->where(‘subcategory_id’, $subcategory_id);
    }
    $query_o = $this->db->get();
    $result_o=$query_o->result();
    $total_rows = COUNT($result_o);

    $row_per_page = 10;
    $begin = ($page – 1) * $row_per_page;
    /*print_r($begin);
    echo “”;*/
    $total_pages = ceil($total_rows / $row_per_page);
    /*print_r($total_pages);
    exit;*/

    if($page db->select(‘subcategory.name_sub as subcategory ,category.name as category,p.*,(SELECT qty FROM `carts` where prodect_id = p.id AND user_id = ‘.$user_id.’ ) as qty_sol,(SELECT id FROM `carts` where prodect_id = p.id AND user_id = ‘.$user_id.’ ) as carts_id,(SELECT is_favorite FROM `favorite` where prodect_id = p.id AND user_id = ‘.$user_id.’ ) as is_favorite’);
    $this->db->from(“products p”);
    $this->db->join(‘category’, ‘category.id = p.category_id’);
    $this->db->join(‘subcategory’, ‘subcategory.id = p.subcategory_id’);
    if(!is_null($category_id) || !is_null($subcategory_id)){
    $this->db->where(‘p.category_id’, $category_id);
    $this->db->where(‘p.subcategory_id’, $subcategory_id);
    }
    if (!is_null($page))
    {
    $this->db->limit($begin,$row_per_page);
    //$this->db->order_by(‘p.id’, ‘ASC’);
    }
    $query_p = $this->db->get();
    echo $this->db->last_query();
    exit;
    $result_p=$query_p->result();
    print_r($result_p);
    exit;
    $data = array();
    if(!empty($result_p))
    {
    foreach ($result_p as $value_p)
    {
    $data[] = array(
    ‘id’=>$value_p->id,
    ‘subcategory’=>($value_p->subcategory == Null) ? ” : $value_p->subcategory,
    ‘category’=>$value_p->category,
    ‘name’=>$value_p->name,
    ‘amount’=>$value_p->amount,
    ‘amount_discount’=>$value_p->amount_discount,
    ‘description’=>$value_p->description,
    ‘cart_id’=>($value_p->carts_id == Null) ? ‘0’ : $value_p->carts_id,
    ‘qty’=>($value_p->qty_sol == Null) ? ‘0’ : $value_p->qty_sol,
    ‘is_favorite’=>($value_p->is_favorite == Null) ? ‘0’ : $value_p->is_favorite,
    ‘images’=>json_decode($value_p->images),
    ‘availability’=>$value_p->availability
    );
    }
    return $data;
    }
    else
    {
    return false;
    }
    }
    else
    {
    echo “string”;
    return false;
    }
    }
    }

  91. Helvis says:

    Thanks Its Working For me…….
    Thank you so much for this post….

  92. Herman says:

    Thank you very much for you tutorial. 11 hours googling, my backbone was hurting so much, but you ´ve save me!!!

  93. aluku says:

    hi,
    its working when i use ($sql=”SELECT * FROM products”;).
    how do i make it work when use filters like ($sql=”SELECT * FROM products WHERE town=’$town’ AND property_type=’$property_type’”;)?
    thanks in advance

  94. Aluku says:

    It works with the 1st page only. Next page is blank.

  95. aluku says:

    hi sir, i shared the code but its not showing here!

  96. aluku says:

    in regards to How to create Pagination with PHP and MySQL

    you asked me to share my codes. when i post they don’t appear here

  97. sobhan says:

    Hello , Thank you for good posting and good tutorial.
    how can I edit code to show last inserted row in the first ?

  98. Ranjit Bhosale says:

    Hello
    i have added same code you have given here inside page but not working properly.

  99. Prachi More says:

    Good blog, Paritosh. The bolg is well written in steps and the entire process of creating pagination with PHP and MySQL is explained well. The blog gives a clear idea as to how to do pagination and the code is also given. The information will be useful for those learning.

  100. Ban says:

    That works just great, thank you, simple and effective !

  101. ADENIYI ARIYO says:

    im having a challege here cos the code below
    $total_pages_sql = “SELECT COUNT(hid) FROM crystalbeds_hotel_info where hotel_region = ‘south_east'”;
    is outputing data even when criteria not met. pls help

    • ADENIYI ARIYO says:

      i was able to solve the problem..didnt include the where clause in the second query
      $sql = “SELECT * FROM crystalbeds_hotel_info where hotel_region = ‘south_east’LIMIT $offset, $no_of_records_per_page

  102. Md Harunur Rashid says:

    Very nice work! it’s working

  103. Marcel van der Stap says:

    I noticed that the script is clear to me . but when i want to use it in my database which works with wampserver my query stops after current page other pages are linked but contain no output

    Is this a wel known problem and how do i solve it

  104. Abdul Manan says:

    Hi, overall all is good but It works with the 1st page only. when we click on Next page, it’s given blank page?

  105. Erol says:

    Wow.Thank you very much.Can you sir explain the”[0]” in “$total_rows = mysqli_fetch_array($result)[0];”. Could don find related explanation.

  106. James Atsaam says:

    Wao!
    I am happy I stumbled over this.
    It did not require much thinking, I implemented it in a blog and it worked without bugs.

    I am so happy.

  107. mathew says:

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

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

    // $paginate.= “$counter

    $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“;}
    // $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.= “$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
    {
    $targetpage = “job_searchs.php?q=result&searchfor=advancesearchs”;
    $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.= “”;

    }

    $number_of_results = mysqli_num_rows($result);
    if($number_of_results > 0) {
    # code…
    while($row = $result->fetch_assoc()) {

    ?>


    account_balance
    .

    .
    place

    Salary-

    <a href="view-jobs.php?id=” class=”part-full-time”>View More

    <?php

    }
    }
    }else
    {
    echo 'No result found!…..’;

    }?>

    keyboard_arrow_left

  108. Emre says:

    Thank you, my other pagingation is bad, i changed, i did it hard for converted sqlite code.

  109. Mubashar Ali says:

    could it be possible to share your codes? atleast the sql query.
    please tell me

  110. Jakob Ward says:

    Nice article. I’m using ColdFusion, but you clearly defined each step and I was able to quickly convert the flow. Thanks!

  111. ranjit says:

    sir please solve first error in code
    i am getting error in $total_rows and my data inside database is is not showing.
    i used different code from another site and those code work!

  112. Kartik Saboo says:

    Hi, Im using PHPSense code for pagination on my website. Currently I have shifted my PHP version from 5.6 to 7.3 and the code stop working. Can you please help me with that.

    Thanks

  113. Jay says:

    Please i’m using your code but when i click on next button, it throws an error that my $_GET[‘santino’] is undefined. The url which when clicked, goes to the pagination page, contains ‘santino’ as the value and that’s the value i use to call the items from the database by using the WHERE clause pointing to ‘santino’. Can you please help me solve it?

  114. its very useful to me thank you so much

  115. Tech-Assured says:

    Fabulous! Well said.
    This was passed on to me by a colleague one notch up leadership from me. I know he has heard me question but this article really put it into perspective.

  116. protips here says:

    its very useful to me thank you so much inquiry visit

  117. Taylor says:

    Hi, when you click on the nav buttons you’re redirected to the top of the page, how do I stop this?

    Apart from this, works great! Thank you

  118. lars says:

    contains ‘santino’ as the value and that’s the value i use to call the items from the database by using the WHERE clause pointing to ‘santino’. Can you please help me solve it?

  119. Stafaband says:

    Thanks you brother, Its very useful to complete my site project

  120. UP Yojana says:

    I want to creat Table of content in my wordpress website using codeing
    how can i create this please reply
    I am also a blogger and I work on my blog UPYojana.net
    Where I shrar UP Government Scheme Related article to Internet User and Readers.

    Recently I write an article on UP Labour Registration Online

    and i want to add table of content in this article by coading.

  121. gianpaolo rossi says:

    thank’s sooooo much
    you ar so generous and really genius
    is useful simple and essential
    🙂

  122. adrian says:

    really understandable even for php noob like me, thanks

  123. SUYASH says:

    Sir you are very great i liked your article i like it

  124. techno gold says:

    thank you, sir, it’s very useful.

  125. Andree says:

    Nice website You are sharing a very informative and great post.I always share it with my friends and relatives 👍

  126. Natalie says:

    Thank you for the super amazing blog, also addding one thing that UI of your website is very interesting.
    Great tutorial of Pagination with PHP and MySql.

  127. Kithra says:

    Very informative website keep sharing boss 👍

  128. aiman says:

    i’m not a programmer.
    can someone help me to insert the pagination script onto my existing script here?

    DEPOSIT MANAGEMENT SYSTEM
    VIEW DEPOSITORIES

    BACK TO SEARCH FORM
    BACK TO MENU

    $value) {

    if ($key != ‘action’) {

    if ($value != ”) {

    $sql .= ‘ and ‘ . $key . ‘ like “%’ . $value . ‘%” ‘;
    $criteria .= $key . ‘=’ . $value . ‘, ‘;

    }
    }

    }

    }

    if ($criteria != ”) {

    $criteria = substr($criteria, 0, strlen($criteria) – 2);

    echo ‘Search criteria: ‘ . $criteria . ”;

    }

    $qry = $db->query($sql);

    if ($qry->num_rows > 0) {
    ?>

    NO
    NAME
    NRIC
    CURR BAL
    DATA TYPE
    DATA SUBTYPE
    ACTION

    fetch_assoc()) {

    $i++;

    ?>

    <a class="hyperlink" href="dep_mgmt_form.php?id=”>VIEW

    DATA NOT FOUNDPlease try again with a new search criteria

    BACK TO SEARCH FORM
    BACK TO MENU

  129. Atul says:

    Very helpful information sir ji

  130. abhi says:

    nice post and good information

  131. Luiz Ribeiro says:

    Brilliant!!

  132. Atul Maurya says:

    thank you so much sir

  133. Zoseme says:

    Nice Information Thanks a lot

  134. govind says:

    nice post and good information

  135. Finally, I found the step-by-step instructions to be incredibly clear and easy to follow. The examples used in the tutorial were practical and relatable, making it easy for me to apply the concepts to my own projects.

    I especially appreciated the attention to detail and the explanations provided for each step. The tutorial covered everything from setting up the database to creating the pagination links, which made it a comprehensive resource for anyone looking to implement pagination on their website.

  136. Great share! .Keep posting more like this!

  137. Markazia says:

    Thanks a lot . Very helpful

  138. vishalkranti says:

    Nice information sir

  139. DearTech says:

    Thanks for sharing!

Leave a Reply

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