What are the benefits of using UNION in a SQL query when working with multiple tables in PHP?
When working with multiple tables in SQL queries in PHP, using UNION allows you to combine the results of multiple SELECT statements into a single result set. This can be useful when you need to retrieve data from different tables that have similar columns or when you want to merge the results of multiple queries into one cohesive dataset.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query using UNION to combine results from two tables
$sql = "SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- How can PHP be optimized to efficiently handle language selection based on user location without compromising performance?
- What are best practices for handling user authentication in PHP applications?
- How can the performance issues related to inserting or updating data in Nested Sets be mitigated in a PHP application?