What are some best practices for handling pagination in PHP to improve user experience?
When implementing pagination in PHP, it is important to consider the user experience to ensure a smooth and efficient browsing experience. Some best practices include limiting the number of visible page links, providing a clear indication of the user's current page, and allowing users to easily navigate to the next or previous pages.
// Example PHP code snippet for handling pagination with improved user experience
// Calculate total number of pages based on total items and items per page
$totalItems = 1000;
$itemsPerPage = 10;
$totalPages = ceil($totalItems / $itemsPerPage);
// Determine current page and limit it within the valid range
$currentpage = isset($_GET['page']) ? $_GET['page'] : 1;
$currentpage = max(1, min($totalPages, $currentpage));
// Display pagination links
echo '<ul class="pagination">';
if ($currentpage > 1) {
echo '<li><a href="?page=' . ($currentpage - 1) . '">Previous</a></li>';
}
for ($i = max(1, $currentpage - 2); $i <= min($totalPages, $currentpage + 2); $i++) {
echo '<li><a href="?page=' . $i . '"' . ($i == $currentpage ? ' class="active"' : '') . '>' . $i . '</a></li>';
}
if ($currentpage < $totalPages) {
echo '<li><a href="?page=' . ($currentpage + 1) . '">Next</a></li>';
}
echo '</ul>';