PDO: MySQL server has gone away

Viewed 92740

I have a script that does a lot of legwork nightly.

It uses a PDO prepared statement that executes in a loop.

The first few are running fine, but then I get to a point where they all fail with the error: "MySQL server has gone away".

We run MySQL 5.0.77.

PHP Version 5.2.12

The rest of the site runs fine.

9 Answers

Most likely you sent a packet to the server that is longer than the maximum allowed packet.

When you try to insert a BLOB that exceeds your server's maximum packet size, even on a local server you will see the following error message on clientside:

MySQL server has gone away

And the following error message in the server log: (if error logging is enabled)

Error 1153 Got a packet bigger than 'max_allowed_packet' bytes

To fix this, you need to decide what is the size of the largest BLOB that you will ever insert, and set max_allowed_packet in my.ini accordingly, for example:

[mysqld]
...
max_allowed_packet = 200M
...

The B.5.2.9. MySQL server has gone away section of the MySQL manual has a list of possible causes for this error.

Maybe you are in one of those situations ? -- Especially considering you are running a long operation, the point about wait_timeout might be interesting...

Try using PDO::setAttribute(PDO::ATTR_EMULATE_PREPARES, true) on your pod instance(s). Dont know that it will help but with no log data its all i got.

It's likely that either your connection has been killed (e.g. by wait_timeout or another thread issuing a KILL command), the server has crashed or you've violated the mysql protocol in some way.

The latter is likely to be a bug in PDO, which is extremely likely if you're using server-side prepared statements or multi-results (hint: Don't)

A server crash will need to be investigated; look at the server logs.

If you still don't know what's going on, use a network packet dumper (e.g. tcpdump) to dump out the contents of the connection.

You can also enable the general query log - but do it very carefully in production.

I got this same error this morning after changing my DB properties in Laravel. I'd commented out the old settings and pasted in new ones. The problem was that the new settings where missing the DB_CONNECTION variable:

DB_CONNECTION=pgsql

Obviously you need to add whatever connection type you are using: sqlite, mysql, ...

Related