I managed to get it mostly working but I still have one problem.
I got rid of all the errors by wrapping the code in an "if SERVER then" if statement. But I still had issues with the script adding the user to the correct usergroup when they joined (saving the groups works fine, but if the player joins the server with a usergroup that doesn't match the database, their usergroup would not change). I fixed this by changing:
"ulx.adduserids(nil,ply:SteamID(),D.groups)"
to
"ulx.adduserid(nil,ply:SteamID(),D.groups)"
Now the script works as I want it to but there is one issue.
My ulx menu seems to fail to load a lot of data. There are no maps in the maps list. There are no adverts in the adverts list (although adverts still display in chat). In the sandbox subtab of the settings tab, no sliders are appearing. In the group manager menu, group members are not appearing, and permissions are not appearing.
I've done some testing over the past few hours and the problems stated above seem to be from the fact I changed "ulx.adduserids(nil,ply:SteamID(),D.groups)" to "ulx.adduserid(nil,ply:SteamID(),D.groups)". If I change it back, all the information is displayed correctly, however the script doesn't change users usergroups.
Any help is appreciated.
Thanks