What are the best practices for handling database queries and result sets in PHP when implementing pagination?

When implementing pagination in PHP with database queries, it's important to limit the number of results fetched from the database to improve performance. This can be achieved by using the LIMIT clause in the SQL query. Additionally, you should keep track of the current page number and calculate the offset for each page to fetch the correct subset of results.

// Calculate pagination variables
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Query database with pagination
$query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);

// Loop through the result set
while ($row = mysqli_fetch_assoc($result)) {
    // Process each row
}

// Display pagination links
// You can use the $page variable to generate pagination links