How can pagination in PHP be limited to a certain number of pages to avoid long lists?
When implementing pagination in PHP, you can limit the number of pages displayed by setting a maximum number of pages to show. This can help avoid long lists and improve user experience. To achieve this, you can calculate the total number of pages based on the total number of items and the items per page, and then limit the displayed page numbers to a certain range around the current page.
<?php
// Calculate total number of pages
$totalPages = ceil($totalItems / $itemsPerPage);
// Limit the number of pages to show
$pagesToShow = 5; // Change this value to adjust the number of pages to display
// Calculate start and end page numbers based on current page
$startPage = max(1, $currentPage - floor($pagesToShow / 2));
$endPage = min($totalPages, $startPage + $pagesToShow - 1);
// Display page numbers within the range
for ($i = $startPage; $i <= $endPage; $i++) {
echo '<a href="?page=' . $i . '">' . $i . '</a>';
}
?>
Keywords
Related Questions
- What is the SQL command to show all databases in a MySQL server using PHP?
- What are the differences between server-side and client-side processing in PHP forms, and how should they be managed for optimal user experience?
- What are the potential issues with including login_einfach.php in multiple files?