When should UNION be used in PHP queries to retrieve data from multiple tables, and what are the benefits of using it?

When you need to retrieve data from multiple tables in PHP, you can use the UNION operator in your SQL queries. UNION is used to combine the results of two or more SELECT statements into a single result set. This can be helpful when you want to fetch related data from different tables and present it as a unified result.

$query = "SELECT column1 FROM table1
          UNION
          SELECT column2 FROM table2";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        // Process the data
    }
} else {
    echo "No results found.";
}