Still wrapping my head around SQL and PHP, but hope someone can help with this:
I have the following tables:
1.
user table
- id
- name
- email
2.
user_group table
- user_id
- group_id
3.
group table
- id
- group_name
There is a many-to-many relationship between the user table and the group table. Now what I am trying to do build a browse users page which lists all the users in the system along with the groups that they belong to, so the page would look something like this:
Name: John Doe
Groups: football, tennis, swimming
Name: Jane Doe
Groups: hockey, basketball
Name: Jim Doe
Groups: hockey, football, rugby
etc. etc.
To accomplish this, I have the following SQL:
SELECT `user`.name, `group`.name
FROM `user`, `user_group`, `group`
WHERE `user`.id = `user_group`.user_id
AND `group`.id = `user_group`.group_id
GROUP BY `user`.id, `group`.id
which returns results as follows:
1. John Doe | football
2. John Doe | tennis
3. John Doe | swimming
4. Jane Doe | hockey
5. Jane Doe | basketball
etc. etc.
As you can see, the results returned need to be manipulated in order to produce the comma separated groups shown earlier, as .
Is there a simple way to get the page to display the groups so that they are in a comma separated list for each user in MySQL? Or do I have to write PHP code to loop through the results looking for duplicate IDs and generating the comma-separated lists of groups on the page? Or am I doing something completely wrong in my approach?
Many thanks.