Where is MySQL Gone Away?

Last Sunday I got to work on a very interesting problem in WordPress which I initially thought could be solved in like 5 mins, but alas it took me almost 7 hours before I found and fixed the problem.

Let me describe the problem, I was running a simple xml parsing script whose task was to parse the xml file and insert the content into WordPress database as a post, everything was working fine except the ‘INSERT’ statement was failing with out any errors. Basically everything would run but nothing would get inserted into database and no errors. We had used the ‘wp_insert_post’ function in  ‘post.php’ file to handle the insertion of post, which was returning ‘0’ instead.

After lot’s of time spend checking and cross checking the sql statements for error and PHP code logic, i finally found the problem which was a small kinda cryptic error ‘MySQL server has gone away’ for every single query that was getting executed in the script.

Well, a quick google search took me to MySQL manual page where it list bunch of possibilities on why the error might be coming.

To me the most logical one were

    1. You tried to run a query after closing the connection to the server. This indicates a logic error in the application that should be corrected.
    2. A client application running on a different host does not have the necessary privileges to connect to the MySQL server from that host.
    3. You have encountered a timeout on the server side and the automatic reconnection in the client is disabled (the reconnect flag in the MYSQL structure is equal to 0).
    4. You can also get these errors if you send a query to the server that is incorrect or too large.
    5. You are using a Windows client and the server had dropped the connection (probably because wait_timeout expired) before the command was issued.

I investigated each one but it turned out that because a query was taking a bit to long to execute MySQL closed the connection and refused all further request from the client.

So you might be wondering what was the Solution to this problem.

Well Rob of Rob’s notebook had the almost perfect solution for it. He created a replacement file for ‘wpdb.php’ which takes care of this problem, yeah it is temporary and you have to remember to replace this file every time you do an WordPress upgrade but it works.

If you are facing this problem go download it and replace you ‘wpdb’ file and save yourself some time.

Check out PHPCamp.net a article sharing website relevant to our own PHP community

2 thoughts on “Where is MySQL Gone Away?

  1. I got the same problem on a custom website based on WordPress and the new file, which opens and closes the connection before every request, solves my problem.

    Thank you for the link you provide.

Comments are closed.