Many WordPress users might be familiar with a screen like this: “Error establishing a database connection.” This page can be displayed for various reasons and no doubt, webmasters hate this error page as it’s a stopping point. In most cases, this error page is displayed because of some server error which might be temporary. In this tutorial, you’ll learn how to create and customize an error page when database stops working.
Basically, with the below code you can create a custom database error page, built specially for WordPress. Also with this code, you can get a notification every time when your website goes down because of database error (optional).
Create a new PHP file and paste the following contents inside that file. Save it as “db-error.php” and place it at /wp-content/ directory.
<?php // custom WordPress database error page
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 600'); // 1 hour = 3600 seconds
// If you wish to email yourself upon an error
// mail("your@email.com", "Database Error", "There is a problem with the database!", "From: Db Error Watching");
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Database Error</title>
<style>
body { padding: 20px; background: red; color: white; font-size: 60px; }
</style>
</head>
<body>
You got problems.
</body>
</html>
Feel free to edit the styling element from this code, to match your site’s look.
With the above code, you won’t get email alerts about database errors. If you want email alerts, then simply remove // before the mail function (on line 8 of the above code).
That’s it, now you’ve got a customized error page in case of database error.
(Code Via)
