How can LEFT JOIN be used in PHP MySQL queries to retrieve incomplete rows from multiple tables?
When using LEFT JOIN in PHP MySQL queries, you can retrieve incomplete rows from multiple tables by including all rows from the left table and matching rows from the right table. This means that even if there is no matching row in the right table, the query will still return the row from the left table with NULL values for columns from the right table. This can be useful when you want to retrieve data from multiple tables but still include rows that may not have a match in the other table.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$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();
?>