How can the use of JOIN statements in SQL queries improve the efficiency of retrieving data from related tables in a PHP application?

Using JOIN statements in SQL queries can improve the efficiency of retrieving data from related tables in a PHP application by allowing the database to combine data from multiple tables in a single query rather than making separate queries for each table. This reduces the number of round trips between the PHP application and the database, resulting in faster data retrieval and improved performance.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// SQL query with JOIN statement to retrieve data from related tables
$sql = "SELECT users.username, orders.order_id, orders.total_amount
        FROM users
        JOIN orders ON users.user_id = orders.user_id";

$result = $conn->query($sql);

// Fetch and display the results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. " - Total Amount: " . $row["total_amount"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the database connection
$conn->close();
?>