How can PHP developers optimize code to handle large query results efficiently?

PHP developers can optimize code to handle large query results efficiently by using techniques such as pagination, limiting the number of results fetched at a time, and utilizing indexes in the database for faster retrieval. By implementing these strategies, developers can prevent memory issues and improve the overall performance of their application.

// Example of implementing pagination to handle large query results efficiently
$page = $_GET['page'] ?? 1; // Get the current page number from the query parameters
$limit = 10; // Number of results to fetch per page
$offset = ($page - 1) * $limit; // Calculate the offset based on the current page

$query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {
    // Process and display the results
}