How can JOIN statements be used effectively in PHP to link related data from different tables?

When using JOIN statements in PHP, you can link related data from different tables by specifying the columns on which the tables should be joined. This allows you to retrieve data from multiple tables based on a common key, enabling you to fetch related information in a single query rather than making multiple queries.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Select data from multiple tables using a JOIN statement
$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);

// Output 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 connection
$conn->close();
?>