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.$conn
is 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 use a variable in a MySQL query using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to get the version of MySQL using PHP?
- How to change database in MySQL with PHP?
- How to generate a UUID in MySQL using PHP?
- How to set a timeout for MySQL query in PHP?
- How to list databases in PHP and MySQL?
- How to return multiple rows as an array in MySQL using PHP?
- How to convert a MySQL timestamp to a datetime in PHP?
See more codes...