What are some best practices for optimizing database queries in PHP when dealing with multiple pages and information retrieval?

When dealing with multiple pages and information retrieval in PHP, it is important to optimize database queries to improve performance. One way to achieve this is by using pagination to limit the amount of data retrieved from the database at once. By fetching only the necessary data for each page, you can reduce the load on the database and improve the overall speed of your application.

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

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

// Loop through results and display data
while ($row = mysqli_fetch_assoc($result)) {
    // Display data here
}