How can SQL joins be effectively utilized to retrieve data from multiple tables in PHP?

To retrieve data from multiple tables in PHP using SQL joins, you can write a SQL query that joins the necessary tables together based on a common column. This allows you to fetch related data from different tables in a single query, reducing the need for multiple queries and improving performance.

<?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 retrieve data from multiple tables using INNER JOIN
$sql = "SELECT t1.column1, t2.column2
        FROM table1 t1
        INNER JOIN table2 t2 ON t1.common_column = t2.common_column";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>