Hello there,
I am back with an easiest way to enrol a student in a course programmatically. Just five line of code to get it done.
Try the below code:
Step-1: Must include the below code at the top of your file.
require_once($CFG->dirroot . '/lib/enrollib.php');
Step-2: Put the enrol_user
function in your PHP script.
function enrol_user($courseid, $userid){
global $DB;
// Enrol the user in the course.
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$maninstance1 = $DB->get_record('enrol', array('courseid' => $courseid, 'enrol' => 'manual'), '*', MUST_EXIST);
$manual = enrol_get_plugin('manual');
$manual->enrol_user($maninstance1, $userid, $studentrole->id);
}
Step-3: Call the enrol_user function.
enrol_user($courseid, $userid)
Happy learning!
Top comments (0)