What are the advantages of using JOIN statements over multiple SQL queries in PHP for data retrieval?

When retrieving data from multiple related tables in a database, using JOIN statements in SQL is more efficient and faster than making multiple queries in PHP. JOIN statements allow you to combine data from different tables based on a common column, reducing the number of queries needed and minimizing data transfer between the database and PHP.

// Using JOIN statement to retrieve data from multiple tables
$query = "SELECT users.username, orders.order_id, orders.total_amount 
          FROM users
          JOIN orders ON users.user_id = orders.user_id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Username: " . $row['username'] . " | Order ID: " . $row['order_id'] . " | Total Amount: " . $row['total_amount'] . "<br>";
    }
} else {
    echo "No results found.";
}