php-mysqlHow to use a MySQL union in PHP?
MySQL UNION is a powerful operator used to combine the result sets of two or more SELECT statements into a single result set. It can be used in PHP to retrieve data from multiple tables in a single query.
Example code
$sql = "SELECT * FROM table1
UNION
SELECT * FROM table2";
$result = mysqli_query($conn, $sql);
Output example
Array
(
[0] => Array
(
[id] => 1
[name] => John
[age] => 25
)
[1] => Array
(
[id] => 2
[name] => Jane
[age] => 30
)
)
Code explanation
$sql: This is the SQL query that contains the UNION operator.mysqli_query($conn, $sql): This is the function used to execute the query.$connis the connection to the MySQL database.UNION: This is the operator used to combine the result sets of two or more SELECT statements into a single result set.SELECT * FROM table1: This is the first SELECT statement used to retrieve data from the first table.SELECT * FROM table2: This is the second SELECT statement used to retrieve data from the second table.
Helpful links
More of Php Mysql
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to change database in MySQL with PHP?
- How to export data from MySQL to Excel using PHP?
- How to check the result of an insert in PHP and MySQL?
- Inserting data to MySQL using PHP
- How to store a boolean value in a MySQL database using PHP?
- How to generate a UUID in MySQL using PHP?
- How to convert a MySQL timestamp to a datetime in PHP?
See more codes...