I actually just noticed a problem that you might not notice for about 8 hours after starting the script, I forgot to put MySQL_close() functions in there... Without these the mysql server will drop the connection after 8 hours of no queries being sent.
I've added them to the original script.