The records having userid=0 suggests something other than Moodle inserted data into the Moodle database, maybe you have a script to populate user enrolment. If so, using the Moodle API instead would avoid these problems.
Also: you should update the site to Moodle 3.7.9. The site is missing over a year's fixes including 29 security updates.