How can one optimize SQL queries in PHP to avoid nested queries within loops?

Nested queries within loops can be a performance bottleneck in SQL queries. To optimize SQL queries in PHP and avoid nested queries within loops, you can use JOINs to combine related tables in a single query. This will reduce the number of queries executed and improve the overall performance of your application.

// Example of optimizing SQL queries using JOINs
$query = "SELECT users.username, orders.order_id, orders.total_amount 
          FROM users 
          JOIN orders ON users.user_id = orders.user_id 
          WHERE users.status = 'active'";

$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        // Process the results
    }
}