How can LEFT JOIN be used to display all records from one table even if there are no matching records in another table in PHP?

When using LEFT JOIN in PHP, you can display all records from one table even if there are no matching records in another table by specifying the LEFT JOIN clause in your SQL query. This will return all records from the left table (the table mentioned first in the query) and matching records from the right table (the table mentioned second in the query), or NULL values if there are no matches. This can be useful when you want to display all records from one table regardless of whether there are corresponding records in another table.

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

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

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

// SQL query using LEFT JOIN to display all records from one table even if there are no matching records in another table
$sql = "SELECT table1.column1, table2.column2
        FROM table1
        LEFT JOIN table2 ON table1.id = table2.id";

$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();
?>