MySQL UNION in PHP

In this article I am going to explain how to use union in PHP.
  • 2139

Introduction Of UNION

A UNION combines the result set of two or more select statements into one result set. The UNION keyword is used to connect two or more SELECT statements but the result of each select statement must have the same number of columns, and the data type of the corresponding columns in each table must be compatible.

Syntax

SELECT statement 1
UNION [ALL]
SELECT statement 2
UNION [ALL]
SELECT statement 2.........................

Example of UNION with PHP

<?php
$
con=mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("mysql", $con);

print "<h2>MySQL: Union through PHP</h2>";

$result = mysql_query("select * from oldempdtl UNION select * from newempdtl");

echo "<table border='1'>

<tr>

<th>EmpId</th>

<th>Firstname</th>

<th>Age</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

   echo "<tr>";

  echo "<td>" . $row['id'] . "</td>";

  echo "<td>" . $row['name'] . "</td>";

  echo "<td>" . $row['age'] . "</td>";

  echo "</tr>";

  }

  echo "</table>";

  mysql_close($con);

  ?>

Note: The example above tells you how to use a union in PHP to combine data from two tables. In this case the oldempdtl table contains the id, name and age of old employees and newempdtl also consists of the id, name and age with additional new employees. This union operation combines all rows of both tables.

Output  

mysql-union-in-php.jpg

© 2020 DotNetHeaven. All rights reserved.