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 utf8mb4_unicode_ci in MySQL with PHP?
- How to convert a MySQL timestamp to a datetime in PHP?
- How to set a timeout for MySQL query in PHP?
- How to output XML from MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to use a variable in a MySQL query using PHP?
- How to check the result of an insert in PHP and MySQL?
- How to update to null value in MySQL using PHP?
- How to get the version of MySQL using PHP?
See more codes...