moodle – Enroll User in a Course


This time for moodlers, have you ever faced such type of need, that you want to enrol user directly in a course using some predefined moodle functions. I was in need for this just after payment success, so thought I should share with you friends..

require("moodle/config.php");

$userid = 'jaswanttak'; // this is user's idnumber
$courseid = 'TEST-01'; // this is course's idnumber

// if you want to use only id than in get_records() you will have to write id in second parameter

$user = get_record("user", "idnumber", $userid);
$course = get_record("course", "idnumber", $courseid);

if (!enrol_into_course($course, $user, 'paypal')) { // paypal is enrollment method for my system you will use yours
echo 'error';
} else {
echo 'success';
}

Cheers,
Jaswant