How can the number of columns in a UNION query affect the results in PHP?

When performing a UNION query in PHP, the number of columns selected in each query within the UNION must match. If the number of columns differs, it can cause errors or unexpected results. To ensure consistent results, make sure the number of columns selected in each query is the same.

<?php
// Example of a correct UNION query with matching number of columns
$sql = "(SELECT id, name FROM table1) UNION (SELECT id, name FROM table2)";
$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo "ID: " . $row['id'] . " Name: " . $row['name'] . "<br>";
    }
}
?>