Hi,
You would have been probably been better of using the Enrolment API - https://docs.moodle.org/dev/Enrolment_API instead of writing to the database directly. You might get an idea of how to achieve that by looking in /lib/enrollib.php specifically the enrol_user() function.
You would have been probably been better of using the Enrolment API - https://docs.moodle.org/dev/Enrolment_API instead of writing to the database directly. You might get an idea of how to achieve that by looking in /lib/enrollib.php specifically the enrol_user() function.