How can the UNION statement be effectively used in PHP to combine data from multiple tables without a common primary key?

When combining data from multiple tables without a common primary key in PHP, you can use the UNION statement to merge the results of separate queries into a single result set. This allows you to retrieve data from different tables that do not share a common key, but have similar columns. By using UNION, you can effectively combine the data and display it as a single result set in your PHP application.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Query to combine data from two tables using UNION
$sql = "SELECT column1, column2 FROM table1
        UNION
        SELECT column1, column2 FROM table2";

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

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

$conn->close();
?>