Skip to main content

Common Moodle programming mistakes

Feel free to add to this list.

Error handling of get_records() and its variants (e.g. get_records_sql())

A common usage of these functions is like this:

$records = get_records_sql($sql)get_records() or my_error_handler();...

ThisThe problem is, if the query is wrong.executed Functionsuccessfully but matches no records, get_records() returns false, the same as if there is an error. That triggers the error handling mechanism and might not be what you want.

Since get_records() and its variants returnscannot tell between these two cases, use them only if you are intentionally not checking for error or if you want to treat the case of no matched record as an emptyerror arraytoo. whenFor other cases, use get_recordset() or its variants. These functions return an ADORecordSet object (if there is no errorerror) and no records are matched, andor false when(if there is an error (e.g. syntax error in the SQL statement)error). However, both values evaluate to false. In the example above, if no records are matched, my_error_handler() will be executed when it should not. The correct way to do error-handling is:

$records = get_records_sql($sql);if ($records === false)  my_error_handler();else  ...