I’m trying to get data from the database in order to create a list of checkboxes, and set them as checked="checked" if the specific user has already checked them last time…
So I have two tables – one is the specialties table, which has the specialty name, and specialty ID.
The other one is the user_specialties, which has a user id (uid) and specialty id (sid)…
The thing is I can’t get a complete list of all the specialties, with the corresponding data from the user_specialties – and don’t know what checkboxes to check…
I tried the following:
function genspecialties($id = 0) {
$query = "select * from specialties s RIGHT JOIN user_specialty us on s.id = us.sid ";
This query will get me the same specialty the number of times as the people have it, multiple times the same specialty for each user… not good :/
so I thought maybe:
$query = "select * from specialties s RIGHT JOIN user_specialty us on s.id = us.sid where us.uid = '$id' ";
But this wasn’t good either, as (of course) it only brought back the specialties that the user have, and skipped those which he do not….
So, maybe anyone have any idea how can I get all the specialties, and a reference if the user has it or not?
I use mysql with PHP…
thanks!
Yanipan
If I’ve understood correctly, this should do what you need:
Edit
Per your request, I’ll go ahead and explain the query. The part that’s probably confusing you is this subquery:
The
IF EXISTStells MySQL to return either TRUE or FALSE if the part immediately following it ‘exists’ (contains a result). TheSELECT * FROM user_specialty us WHERE s.id = us.sid AND us.uid = '$id' LIMIT 1simply tells MySQL to find up a row inuser_specialtywheres.id = us.sid(the speciality ID matches) andus.uid = '$id'(the ID is the user’s).