In what scenarios would using JOINs be more efficient than nested database queries in PHP?

Using JOINs in SQL queries is generally more efficient than using nested queries because JOINs allow the database to retrieve all necessary data in a single query, reducing the number of queries that need to be executed. This can lead to faster execution times and better performance, especially when dealing with large datasets. Nested queries, on the other hand, require multiple separate queries to be executed, which can be slower and less efficient.

// Using JOIN to retrieve data from multiple tables
$query = "SELECT users.name, orders.order_id FROM users
          JOIN orders ON users.user_id = orders.user_id
          WHERE users.user_id = 1";

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

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "User: " . $row['name'] . ", Order ID: " . $row['order_id'] . "<br>";
    }
} else {
    echo "No results found.";
}