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) or my_error_handler();...

This is wrong. Function get_records() and its variants returns an empty array when there is no error and no records are matched, and false when there is an error (e.g. syntax error in the SQL statement). 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  ...