1000 FAQs, 500 tutorials and explanatory videos. Here, there are only solutions!
Error: "Invalid query: MySQL server has gone away"
This type of error often comes from keeping a MySQL connection open without making any requests after a certain time, after which the connection is shut down: http://dev.mysql.com/doc/refman/5.7/en/gone-away.html
The variables wait_timeout and interactive_timeout which control this disconnection are set for 30 seconds: http://dev.mysql.com/doc/refman/5.0/en/communication-errors.html
Execute a script that regularly makes a "ping" or, before launching a query, test if the connection still exists, and where applicable, relaunch it.