How can UNION queries be utilized in PHP to combine multiple SELECT statements for complex data retrieval?

UNION queries in PHP can be utilized to combine multiple SELECT statements to retrieve data from different tables or conditions in a single result set. This can be useful for complex data retrieval where you need to combine data from multiple sources or apply different conditions to fetch the required data.

<?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);
}

// Execute a UNION query to combine multiple SELECT statements
$sql = "(SELECT column1 FROM table1 WHERE condition1)
        UNION
        (SELECT column2 FROM table2 WHERE condition2)";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data from the result set
    while($row = $result->fetch_assoc()) {
        echo "Column: " . $row["column_name"] . "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>