How can the UNION function in PHP be used effectively in SQL queries?
The UNION function in PHP can be used effectively in SQL queries to combine the results of two or more SELECT statements into a single result set. This can be useful when you want to retrieve data from multiple tables or conditions and display them together. By using the UNION function, you can simplify your SQL queries and reduce the need for multiple database calls.
<?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);
}
// SQL query using UNION to combine results from two SELECT statements
$sql = "SELECT column1 FROM table1
UNION
SELECT column2 FROM table2";
$result = $conn->query($sql);
// Display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column Value: " . $row["column1"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>