On a Moodle-enabled site, I want to give users some coupons.
I made it to check if the user is logged in, but I also want to check if the current logged in user is enroled in specific course (an array of 3 course IDs).
So far I tried with $USER->currentcourseaccess
or $USER-> lastcourseaccess
, but they don't do the trick.
So, how can I check if the current logged in user is enrolled in specific Moodle course?
Edit: The site uses Moodle 2.
You can use the table mdl_logstore_standard_log to get the id of the user who created the course. All actions are logged in this table.
Find the user you wish to remove, go to the Status column, and click the trashcan (Delete) icon. Click Unenroll on the confirmation page to approve the change.
I just use this simple 2 line solution (, using course and user id):
global $USER;
$context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST);
$enrolled = is_enrolled($context, $USER->id, '', true);
You'll need to first get the course context, and then check your user against the list of enrolled users with a specific role ID in that context (default role ID for Student is 5). Wit h the Moodle 2.0+ API, you can do it without directly querying the database:
$context = get_context_instance(CONTEXT_COURSE, $course_id);
$students = get_role_users(5, $context);
In Moodle 1.9, you'll need to manually get the stuff from the DB:
mdl_contexts
table with contextlevel = CONTEXT_COURSE (CONTEXT_COURSE = 50)
and instanceid = <id of course>
mdl_role_assignments
with contextid = <first result>
and roleid = 5
you can also run this sql command:
SELECT c.id AS id, c.fullname,c.shortname, u.username, u.firstname,
u.lastname, u.email
FROM mdl_role_assignments ra, mdl_user u, mdl_course c, mdl_context cxt
WHERE ra.userid = u.id
AND ra.contextid = cxt.id
AND cxt.contextlevel = 50
AND cxt.instanceid = c.id
AND u.username = 'User_Username'
AND c.shortname = 'Course_Shortname'
AND (roleid =5 OR roleid=3);
this should check if the user with user name 'User_Username' is enrolled in the course with shortname 'Course_Shortname' as student or teacher
hope it helps.
Enrollment check code snippet :
function check_enrollment($username, $course){
global $DB;
$sql = "SELECT count(*)
FROM mdl_user_enrolments a,
mdl_enrol b,
mdl_user c
WHERE c.username='$username'
AND a.userid=c.id
AND b.courseid=$course
AND a.enrolid=b.id";
$n = $DB->count_records_sql($sql);
if($n==0) {
//user not enrolled
return False;
} elseif($n==1) {
//user already enrolled
return True;
} else {
//, bad data ie<Data sanity not maintained>
add_to_log($course, 'ERROR: check-enrollment', 'Entered into mordor code block');
return False;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With