How to pagine on php

"Learn how to create pagination on PHP with a simple example and code snippets!"

How to Paginate with PHP

Pagination is an important feature for displaying large amounts of data in a user-friendly way. When paginating data, a user is able to quickly find the data they need without having to scroll through a long list of records. This also reduces the amount of server resources needed to retrieve and display a large set of data. In this tutorial, we’ll be learning how to paginate data with PHP. We’ll be using the mysqli extension to connect to our database and retrieve the data.

Connecting to the Database

First, we need to connect to our database. We can do this with the following code:

$host = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database';

$conn = new mysqli($host, $username, $password, $dbname);

if($conn->connect_error) {
  die('Connection failed: ' . $conn->connect_error);
}

Retrieving the Data

Now that we’ve connected to the database, we need to retrieve the data. To do this, we can use a SQL query. For this example, we’ll be retrieving all the rows from a ‘users’ table.

$sql = "SELECT * FROM users";

$result = $conn->query($sql);

if($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    // do something with the data
  }
}

Paginating the Data

Now that we have our data, we can start paginating. To do this, we need to set up a ‘limit’ clause in our SQL query. This will determine how many records are displayed on each page.

$limit = 10; // number of records per page
$offset = 0; // starting record

$sql = "SELECT * FROM users LIMIT $offset, $limit";

$result = $conn->query($sql);

if($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    // do something with the data
  }
}
We can then increment the ‘offset’ variable each time the user clicks on a ‘next’ or ‘previous’ link. We also need to calculate the total number of pages so that we can display the correct number of links. This can be done with the following code:

$sql = "SELECT COUNT(*) as total FROM users";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_pages = ceil($row['total'] / $limit);

Displaying the Links

Finally, we can display the pagination links. We can use a ‘for’ loop to generate the necessary HTML. The following code will generate the links for the first page, a ‘previous’ link, a ‘next’ link and the last page.

echo '
    '; // first page echo '
  • First
  • '; // previous page if($page > 1) { $prev = $page - 1; echo '
  • Previous
  • '; } // next page if($page < $total_pages) { $next = $page + 1; echo '
  • Next
  • '; } // last page echo '
  • Last
  • '; echo '
';
And that’s it! We now have a working pagination system with PHP. We can easily modify this code to suit our needs and display the links in any way we want.

Answers (0)