MySQL server has gone away

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Table of Contents

MySQL documentation

20.8.11. Controlling Automatic Reconnection Behavior
http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
In MySQL 5.0, auto-reconnect was enabled by default until MySQL 5.0.3, and disabled by default thereafter. The MYSQL_OPT_RECONNECT option is available as of MySQL 5.0.13.

Fix

There are many different causes for such an error. The exact fix will depend on the cause.

Timeout

By default, MySQL will close a connection after 8 hours of inactivity. Many hosting providers however will lower that default to a few seconds or a few tens of seconds.

The reconnect flag in the MYSQL structure is set to 0 by mysql_real_connect().

Only those client programs which did not explicitly set this flag to 0 or 1 after mysql_real_connect() experience a change.

Having automatic reconnection enabled by default was considered too dangerous (due to the fact that table locks, temporary tables, user variables, and session variables are lost after reconnection).

The proper fix will depend on whether you have access to the server settings or if you can modify the source code of your application.

On your own development, if you use a php CLI script that requires more than 8 hours (i.e. a script where you might need to have access to the same mysql connection after 8 hours of inactivity), you can:

1) use mysqli instead of mysql (in Drupal, change the $db_url in settings.php to use mysqli instead of mysql). With Ubuntu and probably most distros, mysqli would be installed by default at the same time as mysql, so that if you have the latter installed, the former is probably, too.

AND 2) edit /etc/php5/cli/php.ini thus:

   ; Allow or prevent reconnect
   mysqli.reconnect = On

You can also edit /etc/mysql/my.cnf to increase the timemout delay:

[mysqld]
...
wait_timeout = 432000

On the other hand you want to change your application, you can set the proper flag before using mysql_connect():

my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);

see:
http://dev.mysql.com/doc/refman/5.1/en/mysql-options.html

20.8.11. Controlling Automatic Reconnection Behavior
http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html