How can LEFT JOIN be utilized in PHP to combine data from multiple tables efficiently?

When combining data from multiple tables in PHP, the LEFT JOIN clause can be used to retrieve all records from the left table (the first table mentioned in the query) along with matching records from the right table (the second table mentioned). This is particularly useful when you want to retrieve data even if there are no matches in the right table.

<?php
// Establish a connection to the database
$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);
}

// Query to retrieve data from two tables using LEFT JOIN
$sql = "SELECT table1.column1, table2.column2 
        FROM table1 
        LEFT JOIN table2 ON table1.common_column = table2.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();
?>