Redirect when sql server fails

Submitted by admin on Mar 26, 2010 - 00:00

Some time in Linux based (Free) hosting services the server down occurs only to mysql server. But the apache server works well.

In that time if you are using database connectivity in php code, it will expose error message to the end user.

There is a way to hide the error message and redirect the user to alternate website if you want.

Create a separate file to connect to the mysql server with following script. So on any page you want to connect to the server, just include that script.

The error page is “error/database.php”. As long as you use this script before any output it’s guaranteed to display only the error page when the database fails. In this file you can include script to redirect the user to alternate website you have.


For example, you can let the viewer to visit your blogger blog at the time of your site fails to load.

@mysql_connect(“server”, “username”, “password”) or databasefailure();
@mysql_select_db(“dbname”) or databasefailure();

function databasefailure() {
include “{$_SERVER[“DOCUMENT_ROOT”]}/error/database.php”;

Also, notice the ‘@’ in front of those two lines. Using this character will cause the line to become silent. No run-time errors will be displayed for that line, at all. (Of course syntax errors are still displayed.) Be careful with this though, it will hide any warning or error for that line, which can cause a lot of headache when debugging.

Thanks for marshian at X10