JulianJ JulianJ - 1 year ago 57
PHP Question

How to join three tables and display the result?

I am trying to understand how to join and display data from three tables and have created these three that list person

, types of fruit
and the fruit the people like

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).


$sql="SELECT person.name, favs.fruit_id
FROM person LEFT JOIN favs
ON person.name = favs.person_id
ORDER by person.id";


echo $row['name'];
echo $row['fruit_id'];
echo '<br />';

Answer Source

Ok in your table example data, I assume in table Favs you placed the names for readability, wouldn't it be the IDs themselves. Assuming that is the case using the GROUP_CAT your SQL statement would be:

SELECT p.name, GROUP_CONCAT(ft.name)
FROM favs f
INNER JOIN fruit ft ON ft.id = f.fruit_id
LEFT JOIN person p ON p.id = f.person_id
GROUP BY f.person_id
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download