tags:

views:

231

answers:

5

and the database is MYSQL

A: 

You can write a function which will ping the database via connection and in case it down, reconnect it again and then proceed the query or whatever you want, also take a look on mysqli php library, it can be useful for you.

PS. Also could be useful to implement Singleton design pattern in order to maintain the database connection, once created it will connect to database and then you can implement the method called getConnection which each time will proceed with the check I've described above.

PPS. You can use an exception, try you query, whenever it fails catch an exception, reconnect and try again.

Artem Barger
Will be pretty slow this way,seems?
Shore
What will be slow? To check connection each time? You have to do some trade off, what is more important connectivity assurance or data safety. I would like just to point what any way, to be able to ensure you still have any connection you need to make a check each time, before you start the update. Even if you will succeed to configure mysql server to reconnect automatically on connection lost, it will take time to discover it and maybe you will proceed with query exactly at that time.
Artem Barger
A: 

You can use the mysql_ping() function to test the status of the connection and reconnect when it returns false. mysql_ping() will even reconnect for you if you're using a MySQL before 5.0.13 as mentioned on that documentation page; "Since MySQL 5.0.13, automatic reconnection feature is disabled.".

Garret Heaton
A: 

You should be checking if the query fails anyway. By checking the error code you can tell if it failed because of no connection and reconnect. Just make sure you keep track of reconnection attempts so you don't get stuck in a loop.

A: 

why not use a persistent connection?

Phill Pafford
A: 

Why do you need to "reconnect" in the first place? How/Why are you getting disconnected? In PHP you connect at the beginning of the script and the connection is closed automatically at the end of the script.

There's no need to call mysql_close in your script at all (and it would be silly to "automatically reconnect" if you explicitly closed the connection).

You can try mysql_pconnect is that's what you're looking for. The connection will then stay open permanently, and other scripts that connect can use the connection.

DisgruntledGoat