Are there any recommended best practices for optimizing PHP code to efficiently handle and display large datasets from a database?

When handling and displaying large datasets from a database in PHP, it is important to optimize the code to improve performance. One recommended best practice is to limit the amount of data fetched from the database at once by using pagination. This helps reduce memory usage and speeds up the rendering process.

// Example of implementing pagination in PHP to efficiently handle large datasets from a database

// Define the number of items per page
$itemsPerPage = 10;

// Calculate the offset based on the current page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $itemsPerPage;

// Query the database with LIMIT and OFFSET to fetch only the necessary data
$query = "SELECT * FROM table_name LIMIT $itemsPerPage OFFSET $offset";
$result = mysqli_query($connection, $query);

// Loop through the fetched data and display it
while ($row = mysqli_fetch_assoc($result)) {
    // Display the data
}