1000 FAQs, 500 tutorials and explanatory videos. Here, there are only solutions!
Resolve a MySQL error (server has gone away)
This guide helps resolve an error of type "Invalid query: MySQL server has gone away
".
Preamble
- This type of error often occurs when a MySQL connection is kept open without submitting queries for a period of time beyond which the connection is closed: http://dev.mysql.com/doc/refman/5.7/en/gone-away.html
- The variables
wait_timeout
andinteractive_timeout
that control this disconnection are set to 30 seconds: http://dev.mysql.com/doc/refman/5.0/en/communication-errors.html
Solutions
To avoid the "MySQL server has gone away" error, here are several possible approaches:
Automatic verification and reconnection
Before executing a query, it is recommended to test if the MySQL connection is still active. If the connection has been closed, you can re-establish it automatically before proceeding with your query. Here is an example in PHP:
if (!mysqli_ping($connexion)) {
mysqli_close($connexion);
$connexion = mysqli_connect($host, $user, $password, $database);
}
The function mysqli_ping()
checks if the connection is still valid. If it is not, the script closes the connection and opens a new one.
Sending regular "Pings
Another method involves running a script that regularly sends a "ping" to the database to keep the connection active. For example, you could create a scheduled task (cron job) that sends a light query, such as SELECT 1;
at regular intervals.
Adjusting MySQL parameters (Cloud Server)
With a Cloud Server, you can increase the values of the variables wait_timeout
and interactive_timeout
from the MySQL menu of your server to extend the duration of the connection before it is closed.