## General developer forum

### can I use $DB within theme functions file? can I use$DB within theme functions file?

Hi All,

As with everything this started as a simple addition to my theme, in fact I fully intended to recycle code form a block I developed some time ago but ended up with me banging my head against a wall all evening. I keep getting:

Call to a member function get_records_sql() on null

when I try to use $DB within a theme layout file. The code Im trying works just fine from within a block, is it the context thats messing me up? The code: require_once('../../config.php'); require_login(); global$DB, $OUTPUT,$USER;

and in case it is of any interest, the function:

function checkmodulescomplete($user_id){ $modulecompletions =  $DB->get_records_sql('SELECT * FROM mdl_course_modules_completion WHERE userid = ?', array($user_id));

 return $modulecompletions; }; Average of ratings: - Re: can I use$DB within theme functions file?

Try

{course_modules_completion}  including the braces, in place of the mdl_course_modules_completion. Putting the braces avoids adding the prefix.

Also check that your $user_id is actually passing a value into the function. I think the error you are getting suggests an issue with the sql itself rather than it not recognising the$DB ie, its the 'on null' bit rather than not recognising the function at all.

Note - I'm not really an expert on the database functions, but I do know you can use $DB within themes Average of ratings: Useful (1) Re: can I use$DB within theme functions file?

thanks! I really appreciate the reply,

The code is taken from a block I built, so I wouldn't have thought the sql is causing issues, but I will take your suggestion, and check the user_id while Im at it

Average of ratings: -
Re: can I use $DB within theme functions file? This would be saner version of your function function checkmodulescomplete($userid) {    global $DB;$result = [];    if ($userid) {$result = $DB->get_records('course_modules_completion', ['userid' =>$userid]);    }    return $result;} Average of ratings: Useful (1) Re: can I use$DB within theme functions file?

Sanity has never been my strong suit.

Even the formatting on your code makes me question mine.

Thank you both very much for your time and help. It must have been something in the function (which I refused to believe at the time as I've used it elsewhere). Getting it back to the stage it was at earlier was a pain (I must commit more often) but simply swapping out the function with this sane one did the trick. Resolved!

Average of ratings: -