How can the UNION operator be utilized in PHP to combine and sort data from multiple tables?
To combine and sort data from multiple tables in PHP using the UNION operator, you can create separate SELECT queries for each table, ensuring that the columns selected in each query are the same. Then, use the UNION operator to combine the results from each query into a single result set. Finally, add an ORDER BY clause at the end of the combined query to sort the data as needed.
<?php
// Connect 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);
}
// Create and execute the combined query
$sql = "(SELECT column1, column2 FROM table1)
UNION
(SELECT column1, column2 FROM table2)
ORDER BY column1";
$result = $conn->query($sql);
// Output the sorted and combined data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>