Creating a Page Pagination in PHP Tutorial

Introduction

In this tutorial, I will show you how to Create a Page Pagination in PHP. Using the Page Pagination Feature developer can build an optimized and faster web application, especially for projects with bulk data. The tutorial aims to provide the students or those who are new to PHP Language a guide to learn to enhance their PHP Programming capabilities. Here, I will provide snippets for creating pagination and a usable pagination function that you can also use for your current PHP Project.

What is Page Pagination?

In web development, Pagination is a feature to divide or limit the data on page load. This feature helps to load the web app page faster even if the page content contains a bulk list. This feature is mostly used in tables and lists tags of an HTML.

How to Create Pagination using PHP?

Creating a pagination feature for your PHP Project is not that very complicated. You can achieve it by limiting the data to fetch with the exact order and creating some logic for the pagination buttons. If you are using a MySQL Database, you can use LIMIT and OFFSET to limit and skip data when fetching. You must also use the ORDER clause to properly fetch the exact data for the current page.

PHP Query

Here's a sample MySQL Query in PHP for your pagination.

  1. <?php
  2. // Query Statement
  3. $sql = "SELECT * FROM `sample_tbl` ORDER BY ID ASC LIMIT 10 OFFSET 10";
  4. // Query Execution
  5. $query = $conn->query($sql);

The above query is for fetching the 2nd Page of the Pagination which is limited to 10 rows.

Pagination Button Items

Here is the sample snippet for handling your pagination button items.

  1. <?php
  2. /** Total number or Pagination Buttons
  3.   * $total = the overall data
  4.   * $limit = the limit number per page of the pagination
  5.   */
  6. $pages = ceil($total / $limit);
  7. // pagination items
  8. $page_items = range(1,$pages);

The above snippets demonstrate how to list the page items of the pagination. The first is to divide the overall total of data rows with the pagination limit number. Then range it from 1 to the Quotient to list all the page items.

Usable Pagination Function

Here is a usable PHP Function for your web application pagination. The function is built with required and optional arguments that are relevant for pagination. The function will only work for PHP Project that uses MySQL Database but you can easily customize it if you are using some other database. You will only need to modify the query statement and execution according to the database you are using.

  1. <?php
  2. /**
  3.   * Custom Pagination Function
  4.   * Author: oretnom23
  5.   * Published @ sourcecodester.com
  6.   */
  7. function paginate($tbl="", $order = [] , $limit= 10, $current_page = 1){
  8. // Set Database Connection to Global
  9. global $conn;
  10.  
  11. // Total Data of the table
  12. $total = $conn->query("SELECT * FROM `{$tbl}`")->num_rows;
  13.  
  14.  
  15. // Query Offset
  16. $offset = ($current_page == 1) ? 0 : ($limit * $current_page) - $limit;
  17.  
  18. /**
  19.   * Query Order Clause
  20.   */
  21. $order_by = "";
  22. foreach($order as $k=> $v){
  23. if(!empty($order_by)) $order_by .= ", ";
  24. if(empty($order_by)) $order_by .= " order by ";
  25. $order_by .= " {$k} {$v} ";
  26. }
  27.  
  28. // Query Statement
  29. $sql = "SELECT * FROM `{$tbl}` {$order_by} LIMIT {$limit} OFFSET {$offset}";
  30. // Query Execution
  31. $query = $conn->query($sql);
  32.  
  33. // Queried data array variable
  34. $data = [];
  35. if($query->num_rows){
  36. // Queried data Result
  37. $data = $query->fetch_all(MYSQLI_ASSOC);
  38. }
  39.  
  40. //Display Data i.e 1-10
  41. $displayed_data = ($offset + 1) . "-". ($offset + $query->num_rows);
  42.  
  43. //Check if next pagination button should be available
  44. $has_next = (bool) (($offset + $query->num_rows) < $total);
  45. //Check if previous pagination button should be available
  46. $has_prev = (bool) ($current_page > 1);
  47.  
  48. // Total number or Pagination Buttons
  49. $pages = ceil($total / $limit);
  50. // pagination buttons
  51. $pb = range(1,$pages);
  52. // limit paganation buttons if it is greater than 5 items
  53. if($pages > 5){
  54. if($current_page >= 1 && $current_page <= 3){
  55. // if Active page is between 1-3
  56. $new_pb = range(1, 3);
  57. $new_pb[] = '...';
  58. $new_pb[] = $pb[array_key_last($pb)];
  59. }elseif($current_page >= 4 && $current_page < $pb[array_key_last($pb)]){
  60. // if Active page is between 4-last page number
  61. $new_pb = range(1, 2);
  62. $new_pb[] = '...';
  63. $new_pb[] = $current_page;
  64. if(($current_page +1) != $pb[array_key_last($pb)]){
  65. $new_pb[] = '...';
  66. }
  67. $new_pb[] = $pb[array_key_last($pb)];
  68. }else{
  69. // if Active page is the last page
  70. $new_pb = range(1, 3);
  71. $new_pb[] = '...';
  72. $new_pb[] = $pb[array_key_last($pb)];
  73. }
  74. }
  75.  
  76. // Replace the pagination button with new items if exists
  77. if(isset($new_pb))
  78. $pb = $new_pb;
  79.  
  80. //return pagination object data
  81. return (object) [
  82. 'data' => $data,
  83. 'current_page' => $current_page,
  84. 'displayed_data' => $displayed_data,
  85. 'total' => $total,
  86. 'has_prev' => $has_prev,
  87. 'has_next' => $has_next,
  88. 'pagination_buttons' => $pb
  89. ];
  90. }

Parameters

Here are the following parameters of the above PHP Pagination Function. Make sure to place the parameters in order

  1. Table Name - (string) the table name of the data you wanted to query from your database.
  2. Order By - (array) an array of data composed of a table column as the key and the order position (ASC/DESC) as the value
  3. Limit - (integer) the maximum or limit value of the pagination.
  4. Current Page - (integer) the current page of the pagination. The default value is 1.

Return Values

The PHP Pagination Function returns an object value.

  • data - (array|object) the limited result of the query or fetch data from the database.
  • current_page - (integer) the pagination current page.
  • displayed_data - (string) the fetched data rows i.e. [1-10].
  • total - (integer) overall number of rows of data on the given database table.
  • has_prev - (boolean) returns true if the previous page of pagination is available otherwise false.
  • has_next - (boolean) returns true if the next page of pagination is available otherwise false.
  • pagination_buttons - (array) the list of pagination items for your pagination button. Take note that the ... indicates an ellipsis item which means the page/pages have been truncated.

Example

I have provided a working source code for this tutorial. Download the source code zip file below to test the usable PHP Function I have provided above. The application was developed with CDN external libraries for the icons and the design. Make sure that your local machine is connected to the internet before running the application.

Snapshot

Here is the sample snapshot of the source code result.

PHP Page Pagination

DEMO VIDEO

That's the end of this tutorial. I hope this will help you with what you are looking for and for your future PHP Projects. You can leave a comment below if you have any queries or questions about this tutorial.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment