PHP how to make a pagination

Learn how to create a pagination in PHP with a step-by-step example. Create a smooth navigation to quickly browse through your website's content.

Creating a Pagination with PHP

Pagination is a great way to divide large sets of data into smaller, more manageable chunks. It can help improve user experience on a website by making it easier to navigate through large amounts of data. Pagination also helps save bandwidth by only displaying a few records at a time.

In this tutorial, we will be creating a pagination system with PHP. We will use the mysqli_num_rows() and mysqli_fetch_array() functions to retrieve and count the number of records from a MySQL database. We will then use the ceil() function to calculate the total number of pages. Finally, we will create the pagination links that the user can use to navigate through the various pages.

Step 1 - Connecting to the Database

The first step is to connect to the database. We will use the mysqli_connect() function to do so. Make sure to replace the placeholder values with your own database information.


<?php
// Connect to MySQL
$con = mysqli_connect("localhost","username","password","database");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Step 2 - Retrieving the Records

Now that we have connected to the database, we can retrieve the records from the table. We will use the mysqli_query() function to execute a SQL query. We will also use the mysqli_num_rows() function to count the total number of records.


<?php
// Get the total number of records
$sql = "SELECT * FROM table";
$res = mysqli_query($con,$sql);
$records = mysqli_num_rows($res);
?>

Step 3 - Calculating the Total Number of Pages

Next, we will use the ceil() function to calculate the total number of pages. We will divide the total number of records by the number of records to be displayed per page.


<?php
// Calculate the total number of pages
$pages = ceil($records/$per_page);
?>

Step 4 - Creating the Pagination Links

Finally, we will create the pagination links. We will use an HTML list to display the links. We will also use the $_GET variable to pass the page number to the script.


<?php
// Create the pagination links
echo '<ul class="pagination">';
for ($i=1; $i<=$pages; $i++) {
    echo '<li>'.$i.'</a></li>';
}
echo '</ul>';
?>

That's it! We have successfully created a pagination system with PHP. Now, when a user visits the page, they will be able to easily navigate through the various pages of data. This can help improve user experience and save bandwidth on your website.

Answers (0)