How can a pagination function be implemented in a live search feature using PHP?
When implementing a live search feature in PHP, it's essential to include pagination to display search results in manageable chunks. This can be achieved by keeping track of the current page number and limiting the number of results displayed per page. By incorporating pagination into the live search functionality, users can navigate through search results efficiently.
<?php
// Assuming $searchResults is an array of search results
$resultsPerPage = 10;
$totalResults = count($searchResults);
$totalPages = ceil($totalResults / $resultsPerPage);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $resultsPerPage;
$end = $start + $resultsPerPage;
// Display search results for the current page
for ($i = $start; $i < $end && $i < $totalResults; $i++) {
echo $searchResults[$i] . "<br>";
}
// Display pagination links
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='search.php?page=$i'>$i</a> ";
}
?>
Related questions
-
PHP special characters quotes
-
superglobal $_FILES $HTTP_POST_FILES
-
PHP date function input field