What potential errors or pitfalls should be avoided when using PHP pagination for search results?

One potential error to avoid when using PHP pagination for search results is not properly handling the total number of search results. If the total number of results changes between paginations, it can lead to inconsistent and incorrect pagination. To solve this, always recalculate the total number of search results before displaying the pagination links.

// Calculate the total number of search results
$total_results = count($search_results);

// Set the number of results to display per page
$results_per_page = 10;

// Calculate the total number of pages
$total_pages = ceil($total_results / $results_per_page);

// Get the current page number
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;

// Display pagination links
for ($i = 1; $i <= $total_pages; $i++) {
    echo "<a href='search.php?page=$i'>$i</a> ";
}