How can you efficiently handle pagination in PHP when displaying search results?

When displaying search results in PHP, pagination can be efficiently handled by using the LIMIT and OFFSET clauses in SQL queries. By calculating the total number of results and the current page number, you can determine the appropriate LIMIT and OFFSET values to fetch only the relevant subset of results for each page.

// Assuming $perPage is the number of results to display per page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $perPage;

// Perform search query with LIMIT and OFFSET
$searchQuery = "SELECT * FROM table_name LIMIT $perPage OFFSET $offset";
// Execute the query and display results

// Calculate total number of results for pagination
$totalResults = // Perform another query to count total results
$totalPages = ceil($totalResults / $perPage);

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