How can SQL queries be used to join multiple tables and establish relationships in PHP?

To join multiple tables and establish relationships in PHP using SQL queries, you can use the JOIN clause in your query to combine data from two or more tables based on a related column between them. This allows you to retrieve data from multiple tables in a single query and establish relationships between them.

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

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to join two tables based on a common column
$sql = "SELECT users.username, orders.order_id
        FROM users
        INNER JOIN orders ON users.user_id = orders.user_id";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>