Knowledge base
1000 FAQs, 500 tutorials and instructional videos. Here, there are only solutions!
Troubleshooting a MySQL error (server has gone away)
This guide helps you resolve an error of the type "Invalid query: MySQL server has gone away".
Introduction
- This type of error often occurs when a MySQL connection is kept open without submitting any queries for a period of time exceeding the connection timeout: http://dev.mysql.com/doc/refman/5.7/en/gone-away.html
- The
wait_timeoutandinteractive_timeoutvariables, which 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 whether the MySQL connection is still active. If the connection has been closed, you can automatically re-establish it 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 mysqli_ping() function checks if the connection is still valid. If it is not, the script closes the connection and opens a new one.
Regular "Ping" Sending
Another method is to run 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 lightweight request, such as SELECT 1;, at regular intervals.
Adjusting MySQL parameters (Cloud Server)
With a Cloud Server, you can increase the values of the wait_timeout and interactive_timeout variables from the MySQL menu of your server to extend the connection duration before it is closed.
Link to this FAQ: https://faq.infomaniak.com/499
Has this FAQ been helpful?