If you’re regularly receiving the ‘MySQL server has gone away’ database error in your WordPress 3.3 based blog, then this tutorial is for you.
The error usually occurs at high CPU usage because of MySQL server closing the connection before the full request was made. The error can be rectified by increasing the timeout of the MySQL connection. Here’s how to do it:
Update: It is working fine with WordPress 3.4.1
Editing the wp-db.php file
In order to get rid of the error, we need to place a query in the wp-db.php file to keep the connecting open for a longer duration. Follow these steps to do that:
- Using a FTP client or online file manager, browse to your WordPress’s root folder.
- Move further to the wp-includes sub-directory.
- Open the wp-db.php in a text editor which supports line numbers (NotePad++ or cPanel’s Code Editor recommended).
- Move to line number 1057 (approx., See Screenshot below) and copy > paste the following code there before the $this->dbh query.
$this->query("set session wait_timeout=600" );
- All Done! Save the file and clear the cache, if you’re using a caching plugin.
Alternatively, if you weren’t able to edit the wp-dp.php file correctly, you can download this already edited file (link here), extract the zipped file and upload it to the wp-includes directory.
Why it happens?
Whenever a code makes a call to the MySQL, the connection stays open for sometime so that other queries can be made at the same time without the need to re-open the connection. The connection is auto-closed if it stays idle for more than the duration in ‘wait_timeout‘. The above workaround keeps the connection open for a longer duration and thus prevents such an error.
Checking the default value ‘wait_timeout’
The default value of wait_timeout is usually 10 seconds, but it might be changed by your web host. You can find out the value of wait_timeout set by your web host under Variables tab in phpMyAdmin.
The database errors could be of many forms. Error can look like:
“WordPress database error MySQL server has gone away for query SELECT comment_ID FROM wp_comments WHERE comment_post_ID =”