How does using JOIN in SQL queries compare to running separate queries in PHP for data retrieval?

Using JOIN in SQL queries allows for retrieving data from multiple tables in a single query, which can improve performance and reduce the number of round trips to the database. On the other hand, running separate queries in PHP for data retrieval can lead to increased complexity in the code and potentially slower performance due to multiple database calls. It is generally recommended to use JOINs in SQL queries whenever possible to efficiently retrieve related data.

<?php
// Using JOIN in SQL query
$query = "SELECT users.name, orders.order_id FROM users JOIN orders ON users.user_id = orders.user_id";
$result = mysqli_query($connection, $query);

// Fetch data from the result set
while ($row = mysqli_fetch_assoc($result)) {
    echo "User: " . $row['name'] . " - Order ID: " . $row['order_id'] . "<br>";
}

// Free result set
mysqli_free_result($result);

// Close connection
mysqli_close($connection);
?>