What are some best practices for implementing a pagination function in PHP?

Implementing a pagination function in PHP allows you to display a large set of data in smaller, more manageable chunks. This helps improve user experience by breaking up content into easily digestible pages. To implement pagination in PHP, you need to calculate the total number of pages based on the total number of records and the desired number of records per page, then display the appropriate subset of records on each page.

// Pagination function
function paginate($total_records, $records_per_page, $current_page) {
    $total_pages = ceil($total_records / $records_per_page);
    
    // Calculate the offset for the SQL query
    $offset = ($current_page - 1) * $records_per_page;
    
    // Display the records for the current page
    // Example SQL query: SELECT * FROM table LIMIT $offset, $records_per_page
    echo "Displaying records $offset to " . min($total_records, $offset + $records_per_page) . " of $total_records total records";
    
    // Display pagination links
    for ($i = 1; $i <= $total_pages; $i++) {
        echo "<a href='?page=$i'>$i</a> ";
    }
}