In this article, we will learn how to create pagination in php.
To create pagination in PHP, you will need to do the following steps:
- Define the number of records to be displayed per page and the current page number.
- Retrieve the total number of records from your database.
- Calculate the number of pages required based on the total number of records and the number of records to be displayed per page.
- Construct the SQL query with the LIMIT and OFFSET clauses to retrieve the records for the current page.
- Execute the SQL query and retrieve the records.
- Display the records and create links to navigate to the previous and next pages.
Here's an example code that implements pagination in PHP:
<?php
// total number of records
$total_records = 1000;
// number of records per page
$records_per_page = 10;
// calculate total number of pages
$total_pages = ceil($total_records / $records_per_page);
// get current page number from URL
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
// calculate starting record number
$starting_record = ($current_page - 1) * $records_per_page;
// retrieve records from database
$sql = "SELECT * FROM my_table LIMIT $starting_record, $records_per_page";
$result = mysqli_query($connection, $sql);
// display records on the current page
while ($row = mysqli_fetch_assoc($result)) {
echo $row['column1'] . ' ' . $row['column2'] . '<br>';
}
// create links to previous and next pages
if ($current_page > 1) {
echo '<a href="?page=' . ($current_page - 1) . '">Previous</a> ';
}
if ($current_page < $total_pages) {
echo '<a href="?page=' . ($current_page + 1) . '">Next</a> ';
}
// create links to first and last pages
if ($current_page > 1) {
echo '<a href="?page=1">First</a> ';
}
if ($current_page < $total_pages) {
echo '<a href="?page=' . $total_pages . '">Last</a> ';
}
?>