Your code looks great but unfortunately, I'm not quite sure how to integrate it into the existing script I use, sorry.
However, I've been creating a new version of the script with all the field names matching the database as you suggested but am not quite there yet.