PHP AND MySQL - JOIN
JOIN in SQL combines records from 2 tables in a database. Often we might need to extract daata from 2 or more tables and then we need Joins. It simply is an act of joining 2 or more tables in a single temporary table.
Example:
DepartmentTable
| DepartmentId |
DepartmentName |
| 21 |
Sales |
| 32 |
Technical |
| 12 |
HR |
| 15 |
Clerical |
EmployeeTable
| EmployeeName | DepartmentId |
| Mohan |
32 |
| David |
12 |
| Bruce Lee |
15 |
| Jackie Chan |
12 |
| Tom cruise |
21 |
Assume we have 2 tables as mentioned above. And we need to list people in each department. We can do this using a simple Join as follows:
"Select EmployeeTable.EmployeeName, DepartmentTable.DepartmentName from EmployeeTable, DepartmentTable where EmployeeTable.DepartmentId = DepartmentTable.DepartmentId";
This is a "simple join" that fetches results from 2 tables and display it. The result is:
| EmployeeName |
DepartmentName |
| Mohan | Technical |
| David | HR |
| Bruce Lee | Clerical |
| Jackie Chan | HR |
| Tom cruise | Sales |
The Code in PHP for the same would be :
<?php
// Make a MySQL Connection
// Construct our join query
$query = "Select EmployeeTable.EmployeeName, DepartmentTable.DepartmentName from EmployeeTable, DepartmentTable where EmployeeTable.DepartmentId = DepartmentTable.DepartmentId";
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['EmployeeName']. " - ". $row['DepartmentName'];
echo "<br />";
}
?>
This was a simple join used to fetch and display result from 2 tables. We'll now move to LEFT and Other Joins.

Post Comment