WordPress: Error establishing a database connection

If this error message does not trigger a response from the monitoring service you use, you can create a file in the root folder and have the monitor check that specific file.

I’ve been using StatusCake since 2017 or thereabouts.
They send out warnings to my email address, a message on Telegram, and SMS.

<!DOCTYPE html>
<html>
<head>
<title>Database connectivity test | <?php echo $_SERVER['SERVER_NAME'] ?></title>
</head>
<body>
<?php

// Try to load the database connection information
@include( 'wp-config.php' );

if( !defined( 'DB_NAME' )) {
	// The config file could not be found - no testing possible, report an error so this can be fixed
	http_response_code(503);
	echo "Config not found.";
} else {
	try {
		// Attempt to connect
		$mysqli = new mysqli(
			"localhost",
			DB_USER,
			DB_PASSWORD,
			DB_NAME
		);

		// Check connection
		if( $mysqli->connect_errno ) {
			http_response_code(503);
			echo "Error connecting to database: " .$mysqli->connect_error;
		} else {
			echo "OK";
		}
	} catch( Exception $e ) {
		http_response_code(503);
		echo "Error connecting to database: " . $mysqli -> connect_error;
	}
}
?>
</body>
</html>

Additionally and alternatively, if you can create a file db-error.php and store it in the wp-content folder, WordPress will show that file instead of the dreaded standard one, in case the database server goes away.