1) check the data type... If you expect an email, use FILTER_VALIDATE_EMAIL, if you expect a number use is_numeric, ...
2) clean all the input, unless it's a variable you got from a trusted source that was previously cleaned (for example, data you fetch from your database, and that was verified and clean when it was entered)
3) start using prepared statements
4) lock down your database privileges. Make sure the mysql user entered in your config file only has the privileges he really needs to perform his tasks... If the user doesn't need "insert" privileges on a certain table, make sure he doesn't have this privilege...
You could also doublecheck the owners of these php files and the folders, and the file/folder permissions...
Can you share the url where you installed this vulnerable script? I can do a quick vulnerability scan when i get home... It's usually easyer to work this way than to browse trough your sourcecode
Also, the accesslog from around the time where you were breached might be interesting information.
Once again: i didn't really dig into your sourcecode... The things i said in this post are merely good housekeeping rules i use myself when writing scripts... It's possible the attacker used a completely different attack vector