Solution to “MySQL Server Has Gone Away” Problem

Seriously guys, I got this error and I was laughing hard. The error is just too funny, don’t you think? Yes, it is but not for developers like me. Problem to this error is almost undetectable and there are more than a dozen reasons as to why this occurs and this often baffles developers.

This error generally comes when :

MySQL connection times out.

The MySQL server shuts down.

The connection is interrupted.

The query you are performing is too large for server to handle.

The query you are performing takes more space than allowed (default: 16MB).

While these are some common reasons, there maybe some unknown reasons to come across this error. I faced one of those unknown reasons.

My PHP code looked somthing like this:

<?php

function one()

{

….

}

function two()

{

….

}

function connect2db()

{
…..    //this connected to db

}

// Around 10 more functions

// Then:

connect2db();

one();

two();

/* Couple more function calling, a few loops, a few conditions and then the query: */

query = “Select id from users”;

$result = mysql_query($query) or die(mysql_error());

?>

I just tried so many solutions to solve the problem. I copied the query and pasted it in phpmyadmin to check if there was a problem with the query but it was not. The problem was on the PHP side.

When I tried everything else, including repairing and optimizing the tables and changing tables’ engine to innoDB, and the problem wasn’t solved, I just changed my code to immediately execute the query after the connection. For that I modified my code to look like this:

<?php

function one()

{

….

}

function two()

{

….

}

function connect2db()

{
…..    //this connected to db

}

// Around 10 more functions

// Then:

one();

two();

/* Couple more functions calling, a few loops, a few conditions and then the query: */

query = “Select id from users”;

connect2db();

$result = mysql_query($query) or die(mysql_error());

mysql_close();

?>

I did this at every instance of query, and voila the problem disappeared.

Happy developing, Guys!

Cheers!

Leave a comment

Your email address will not be published.