Jul 19, 2009
Solution to “MySQL Server Has Gone Away” Problem
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!

You’re doing it wrong.
Geez Josh, that’s an awefully helpful comment there.
@Josh
That worked for me, so I am happy with it. Can we know your solution too?
@Paul
Didn’t get ya… are your supporting Josh or going against him?
Thanks worked fine for me…
Most welcome. At least it worked for you.
In my case it was mostly because of reached maximum connections limit.
I fixed it by:
- lifting maximum_connections number
- limiting maximum concurrent connection per user (without that one buggy site could stop whole MySQL server – I didn’t like it)
@Mariusz Nowak
Hah, so you are server admin. Cool.
BTW: Your using the same template as I’m using xD
Seriously, I didn’t get what you wanted to show in this one.
@rave
Well, I gave a solution to one of the most annoying error occuring in MySQL.