What is the significance of using UNION All when querying from multiple tables in PHP?
When querying from multiple tables in PHP, using UNION All allows you to combine the results from multiple SELECT statements into a single result set. This can be useful when you want to retrieve data from different tables that have similar columns or when you want to combine data from multiple sources.
<?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 using UNION All to retrieve data from multiple tables
$sql = "SELECT column1, column2 FROM table1
UNION ALL
SELECT column1, column2 FROM table2";
$result = $conn->query($sql);
// Output the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>