PHP AND MySQL - JOIN

Submitted by programmer on Tue, 07/31/2007 - 11:05.
::

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['Employee
Name']. " - ". $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 your Answer

  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Links to specified hosts will have a rel="nofollow" added to them.

More information about formatting options