Share
MySQL Join Example
Let's imagine that we wanted to SELECT all the dishes that were liked by a persons. If you remember from the previous lesson, this is a situation when we need to use the WHERE clause. We want to SELECT all the dishes WHERE a persons likes it.
We will be performing a generic join of these two tables using the Name column from each table as the connector.
Note: This example assumes you have created the MySQL tables "food" and "person". If you do not have either of them created, you can either create them using our MySQL Create Table lesson or do it manually yourself.
PHP and MySQL Code
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT person.Name, food.Meal ".
"FROM person, food ".
"WHERE person.Name = food.Name";
$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['Name']. " - ". $row['Meal'];
echo "
";
}
?>
The statement "WHERE person.Name = food.Name" will restrict the results to the rows where the Name exists in both the "person" and "food" tables.
Results
Putu - Ayam Betutu
Made - Tipat Cantok
Nyoman - Nasi Jinggo
Ketut - Lawar
Those are the results of our PHP script. Let's analyze the tables to make sure we agree with these results.