tags:

views:

57

answers:

2

I have a cron job that runs every minute. Every once in a while the cron fails with the error:

MySQL server has gone away

The problem is that all the query below this error are executed and may sometimes give undesirable result.

So how do I detect that the error has occurred and exit execution of rest of the code?

Or any hint on how to fix the error in the first place would be great.

A: 

A quick fix is to turn off persistent mysql connections. A better fix is to catch that specific error and call a reconnect (PDO::__construct) until you get an instant that has a live connection. I find I often get this error when the server computer goes to sleep or if the mysql connection timeout is to low.

Kendall Hopkins
how to turn off persistent mysql connections?
Yeti
Are you using PDO or mysql_* or mysqli?
Kendall Hopkins
Uh, not sure really. I'm not a php/mysql guy really and use EZSQL to deal with SQL.
Yeti
A: 

The error seems to be caused by connecting to a server that isnt responding, or you are using a persistent connection that is timing out.

You should be able to get some kind of error code from the client API, and catch to see if the connection is still valid.

If it has failed, you can throw an exception, and then stop the program.

$query_id = mysqli_query($conn_id, $query);
if(!$query_id )
{
    // throw an exception
    throw new DatabaseQueryException("An error occurred accessing the database.\nError: \n".mysqli_error($conn_id));
}

Is what I use on my site

webdestroya
can you give a small code snippet?
Yeti
@Lost_in_code there you go, I added a pretty simple one. You would obviously need to replace 'DatabaseQueryException' with a custom one (or do `class DatabaseQueryException extends Exception {}`)
webdestroya