I am trying to understand how to join and display data from three tables and have created these three that list person (person), types of fruit (fruit) and the fruit the people like (favs).
Person Fruit Favs
id | name id | type id | person_id | fruit_id
1 | Peter 1 | apple 1 | Peter | orange
2 | Sue 2 | orange 2 | Sue | apple
3 | John 3 | banana 3 | John | banana
4 | Mary 4 | Peter | apple
5 | Sue | orange
My aim is to learn how to join all three tables and display which fruits (if any) the people like. Just like this:
Peter | orange, apple
Sue | apple, orange
John | banana
Mary |
I just about understand how to join all three tables to display the data above but the thing that really confuses me is how to echo out the results. Should I be using nested while loops or a foreeach loop? I've got so confused and would really appreciate someone showing me the way. The closest I've got is this (which is far off I know).
<?php
$sql="SELECT person.name, favs.fruit_id
FROM person LEFT JOIN favs
ON person.name = favs.person_id
ORDER by person.id";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
echo $row['name'];
echo $row['fruit_id'];
echo '<br />';
}