SQL query to find currently enrolled students

SQL query to find currently enrolled students

by John Houser -
Number of replies: 4
I've been writing some scripts that help to integrate our Moodle system with a separate, external workshop scheduling database which drives our website. One script requires that I extract from the Moodle database a list of currently enrolled students for a course, given a course ID number. The current query looks like this:

SELECT u.username, u.firstname, u.lastname, u.email, c.fullname workshop
FROM mdl_user u, mdl_role_assignments r, mdl_course c, mdl_context t
WHERE t.instanceid = c.id
AND r.contextid = t.id
AND r.userid = u.id
AND r.roleid = 5
AND u.deleted != 1
AND c.idnumber = $course_idnumber

The query works except that it returns both currently enrolled students and previously enrolled students. I've noted that mdl_context includes a column called contextlevel and that that column has one number for all the current students and another number for old students. But I don't know how to predict what the correct contextlevel should be for a given course. Can anyone explain how the contextlevel works?

Any help would be greatly appreciated!
Average of ratings: -
In reply to John Houser

Re: SQL query to find currently enrolled students

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
Context level actually tells you what type of context you have. So if contextlevel = 50, then you have a course, and instanceid is a course id. If contextlevel = 10 then this is the site context, and there should only be one. context_level = CONTEXT_MODULE (these contstants are defined at the top of lib/accesslib.php) then instanceid points to the course_modules table.
Average of ratings: Useful (1)
In reply to John Houser

Re: SQL query to find currently enrolled students

by yuki yuki -
Your query is giving results who are locally assigned (suppose course->assign roles)...
but when a user assigned globally meaning assign roles in system (Users->Permission->Assign system roles) then how to get those users by query?. Can you please give me the hints/or that query?