What are common pitfalls when using UNION in PHP to query multiple tables?

Common pitfalls when using UNION in PHP to query multiple tables include not properly sanitizing input data, not handling potential errors, and not optimizing the query for performance. To solve these issues, ensure that input data is sanitized to prevent SQL injection attacks, handle any potential errors that may arise during the query execution, and optimize the query by selecting only the necessary columns and using indexes where appropriate.

<?php

// Sanitize input data
$input = $_GET['input'];
$sanitized_input = mysqli_real_escape_string($conn, $input);

// Query using UNION with sanitized input
$query = "SELECT column1, column2 FROM table1 WHERE column3 = '$sanitized_input'
          UNION
          SELECT column1, column2 FROM table2 WHERE column3 = '$sanitized_input'";

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

// Handle potential errors
if (!$result) {
    die('Error: ' . mysqli_error($conn));
}

// Process the query results
while ($row = mysqli_fetch_assoc($result)) {
    // Do something with the data
}

?>