What role does the LEFT JOIN function play in querying databases in PHP and how can it be utilized in this scenario?
When querying databases in PHP, the LEFT JOIN function is used to retrieve data from multiple tables based on a related column between them. It includes all the rows from the left table and the matched rows from the right table, even if there are no matches found. This can be useful when you want to retrieve data from one table regardless of whether there is a matching row in the other table.
<?php
// Connect to 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 using LEFT JOIN
$sql = "SELECT orders.order_id, customers.customer_name
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Order ID: " . $row["order_id"]. " - Customer Name: " . $row["customer_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>