get_records_sql always returns same id for users

get_records_sql always returns same id for users

by electo TheBledard -
Number of replies: 3

Hello,

I'm trying to get all the users who are in a certain cohort and enrolled in a certain course. But i don't know why when i use get_records_sql() the function returns the correct users but they doesn't have the correct id. The id's should be 2, 3, and 4 but i always get 4 for each user.


Here's my sql statement:

SELECT * FROM {user} user JOIN {cohort_members} cohort ON user.id = cohort.userid JOIN {user_enrolments} userenrol ON user.id = userenrol.userid JOIN {enrol} enrol ON userenrol.enrolid = enrol.id WHERE 1 = 1 AND cohort.cohortid = 1 AND enrol.courseid = 3

// Here the cohort is 1 and the course is 3

// Don't take note of the '1 = 1'

This should return 3 users whith the ids 2, 3 and 4 but it only returns 1 user with the id 4 (that's because get_records_sql() regroups them because he finds the same id for all)


Of course when i try this statement in phpmyadmin it works perfectly...


Please help me i don't know what to do anymore... sad

Average of ratings: -
In reply to electo TheBledard

Re: get_records_sql always returns same id for users

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Just make your list of fields more specific? You don't seem to say which id you are looking for but 'SELECT *' is asking for trouble. Make a specific list rather than just a *

Average of ratings: Useful (1)
In reply to Howard Miller

Re: get_records_sql always returns same id for users

by electo TheBledard -

Omg! It worked! Thank you so much!
I didn't knew that doing 'SELECT *' was dangerous. I've been doing this for a year and i never had any problems with the '*'.
Thanks again!

In reply to electo TheBledard

Re: get_records_sql always returns same id for users

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Yeh - the database abstraction library relies on a unique 'id' field being returned. This makes 'SELECT * ... JOIN ... JOIN ... JOIN ...' and the like a bit risky as there will be multiple id fields to choose from. It's always better to be explicit. Only use 'SELECT *' when it's a single table. 

If the tables are large, it may not scale very well either. 

Average of ratings: Useful (1)