How can the SQL query in the PHP code be optimized to avoid multiple database queries within a loop?

The issue of multiple database queries within a loop can be solved by fetching all the necessary data in a single query before entering the loop. This can be achieved by using a JOIN statement or a subquery to retrieve all the required data in one go. By doing so, the loop can then iterate over the fetched data without the need for additional queries within the loop.

// Fetch all necessary data in a single query
$query = "SELECT orders.order_id, orders.total_price, customers.customer_name 
          FROM orders 
          INNER JOIN customers ON orders.customer_id = customers.customer_id";
$result = mysqli_query($connection, $query);

// Check if the query was successful
if($result){
    // Iterate over the fetched data
    while($row = mysqli_fetch_assoc($result)){
        // Process each row as needed
        echo "Order ID: " . $row['order_id'] . " - Total Price: " . $row['total_price'] . " - Customer Name: " . $row['customer_name'] . "<br>";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}

// Free the result set
mysqli_free_result($result);