Is it possible to have multiple SELECT statements in a single SQL query in PHP?
Yes, it is possible to have multiple SELECT statements in a single SQL query in PHP. You can use UNION or UNION ALL to combine the results of multiple SELECT statements into a single result set. Make sure that the number of columns and their data types match in all SELECT statements.
<?php
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare the SQL query with multiple SELECT statements using UNION
$sql = "SELECT column1 FROM table1
UNION
SELECT column2 FROM table2";
// Execute the query
$stmt = $pdo->query($sql);
// Fetch and display the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['column1'] . "<br>";
}
?>
Keywords
Related Questions
- What are common mistakes beginners make when trying to use PHP for form submissions?
- In the context of PHP socket operations, how can different return codes like 87 and 88 impact the functionality of the code and what steps can be taken to address them?
- What steps can be taken to troubleshoot and debug issues with updating database entries using arrays in PHP?