General developer forum

get_records_sql returns one user/course/activity/etc when there are many

 
Davo
Re: get_records_sql returns one user/course/activity/etc when there are many
Core developersParticularly helpful MoodlersPlugin developers

As stated in the docs https://docs.moodle.org/dev/Data_manipulation_API#Getting_an_hashed_array_of_records the array returned by all of the get_records* functions in Moodle is indexed by the first field in the SELECT.

So, if you set the first field to c.id, then you will only get a single record for each course, as the others will be overwritten.

If you have Debugging on (as you should always have for any development), then you will get a warning message about this.

Solutions:

1. Choose a different field at the start of the SELECT statement (ra.id would be a good choice in this case)

2. Use one of the get_recordset* functions and loop through the results with foreach (this also reduces memory usage, but has less flexibility as you can only loop through the results, you cannot use any of the usual array manipulation functions on them).


 
Average of ratings: -