Using WordPress ‘dead_db()’ PHP function

The dead_db() WordPress PHP function is responsible for loading custom database error messages. If a file named db-error.php is found in the wp-content directory, this function will load that file. If the file is not found, the WordPress database error will be displayed. The function ensures the HTTP status header is set to 500 to prevent search engines from caching the error message. Custom database error messages should adhere to the same standard.

Usage

To use the dead_db() function, you simply need to call it when a database error occurs. Here’s an example:

if (!$wpdb->check_connection()) {
dead_db();
}

In this example, if the database connection check fails, the dead_db() function is called to handle the error display.

Parameters

The dead_db() function does not require any parameters.

More information

See WordPress Developer Resources: dead_db()

This function was backported to WordPress 2.3.2, but originally it was introduced in WordPress 2.5.0.

Examples

Basic Usage

// Check if database connection exists
if (!$wpdb->check_connection()) {
// Load custom DB error or display WordPress DB error
dead_db();
}

In this example, the dead_db() function is called when a database connection does not exist.

Within a Try/Catch Block

try {
$wpdb->query('SELECT * FROM nonexistent_table');
} catch (Exception $e) {
dead_db();
}

In this scenario, when a query to a non-existing table is attempted, the dead_db() function is invoked to handle the error.

Within a Function

function my_custom_query() {
global $wpdb;

$results = $wpdb->get_results("SELECT * FROM wp_posts");

if (!$results) {
dead_db();
}
}

Here, the dead_db() function is used within a function that queries the wp_posts table. If no results are returned, the database error is handled.

In a Plugin

function my_plugin_activate() {
global $wpdb;

if (!$wpdb->check_connection()) {
dead_db();
}

// rest of the plugin activation code...
}

register_activation_hook(__FILE__, 'my_plugin_activate');

In this example, the dead_db() function is used in a plugin activation hook. If the database connection is not available, the function handles the error.

In a Theme

function my_theme_setup() {
global $wpdb;

if (!$wpdb->check_connection()) {
dead_db();
}

// rest of the theme setup code...
}

add_action('after_setup_theme', 'my_theme_setup');

Here, the dead_db() function is used in a theme setup function. If there’s no database connection, the function handles the error.