Why don't you use the external database enrollment option and save re-inventing the wheel?
If it helps here the jist of how I've setup enrollments at the college I work at.
I created a view in the MIS system database that lists enrollments - it lists the student refernece and the id number of the course. This is exported to a table in the Moodle database
nightly.
Our courses in moodle are setup with the MIS id number in the ID Number field in course settings. Users login using their network login credentials (
LDAP authentication coupled with AD) for students this happens to be their student reference number.
The external database enrollment is setup in moodle, which looks through the table we import into and creates those enrollments for that student each time they login.
Its been running like that for a few months now and were pretty happy with it - it seems to have been very robust and it was very simple to setup.
Not sure if thats what your trying to achieve, but if it is it might save you some work.
Rick