How can the UNION function in MySQL be utilized to simplify and optimize PHP code for querying a database?

Using the UNION function in MySQL can simplify and optimize PHP code for querying a database by allowing multiple SELECT statements to be combined into a single result set. This can reduce the number of queries that need to be executed and streamline the code for better performance.

<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query using UNION to combine multiple SELECT statements
$query = "SELECT column1 FROM table1
          UNION
          SELECT column2 FROM table2";

$result = mysqli_query($connection, $query);

// Fetch and output the results
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['column1'] . "<br>";
}

// Close the connection
mysqli_close($connection);
?>