How can UNION ALL be used in PHP to combine data from multiple tables efficiently?

When combining data from multiple tables efficiently in PHP using UNION ALL, it is important to ensure that the columns selected from each table match in number and data type. This will prevent errors and ensure a successful combination of data. Additionally, using UNION ALL instead of UNION can improve performance as it does not remove duplicate rows.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "(SELECT column1, column2 FROM table1)
        UNION ALL
        (SELECT column1, column2 FROM table2)";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>