How can UNION be used in PHP to combine multiple SQL queries into a single result set?

To combine multiple SQL queries into a single result set in PHP, you can use the UNION operator in your SQL query. The UNION operator allows you to combine the results of two or more SELECT statements into a single result set. This can be useful when you need to retrieve data from multiple tables or conditions and present it as a single result set.

<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// SQL query using UNION to combine multiple queries
$sql = "(SELECT column1 FROM table1)
        UNION
        (SELECT column2 FROM table2)
        UNION
        (SELECT column3 FROM table3)";

// Execute the query
$result = $connection->query($sql);

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

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