Jump to content

Email script to check for a downed database?


Jeffro

Recommended Posts

I have a couple hundred websites that I run a php/mysql script on.  Every couple weeks, I manually visit every site to ensure it's up and running.  Without fail, there's always one or two that have a message indicating the database has crashed.  I run some pretty big cron jobs on them every night.. so it just happens. 

 

Can someone recommend a way that I could poll all of my mysql databases and somehow email/alert me when one goes down? 

 

Thoughts?

 

Thank you. 

something like this?

 

<?php
echo '<html><head></head><body>';
//check function
$messages = 'Database check Return<br> ';

function chk_db( $dbhost, $dbname, $dbuser, $dbpass, $prefix='' )
{
	global $messages;
	$prefix = $prefix;
	$dbname = $dbname;

	if( empty($dbpass) )
	{
		$link_id = @mysql_connect($dbhost, $dbuser);
	}
	else
	{
		$link_id = @mysql_connect($dbhost, $dbuser, $dbpass);
	}

	@mysql_query("SET NAMES 'utf8'");

	if( (is_resource($link_id)) && (!is_null($link_id)) && ($dbname != '') )
	{
		if( !@mysql_select_db($dbname, $link_id) )
		{
			@mysql_close($link_id);
			$table = '( <span style="color:ff0000">DB named '.$dbname.' failed to connect</span> )';
		}
		$messages .= '<span style="color:99ff33">DB '.$dbhost.' Connected '.$table.'</span><br>';
	}
	else
	{
		$messages .= '<span style="color:ff0000">DB '.$dbhost.' ('.$dbname.') failed to connect</span><br>';
	}
	return true;
}

#
#	now creat an array with the mysql info
#	for all the databases you need to check...
#
$array = array(
		array(
			'dbhost' => 'localhost',
			'dbuser' => 'root',
			'dbname' => 'wowroster',
			'dbpass' => '',
			'prefix' => '',
		),
		array(
			'dbhost' => 'localhost',
			'dbuser' => 'root',
			'dbname' => 'avg',
			'dbpass' => '',
			'prefix' => '',
		),
		array(
			'dbhost' => 'localhost2',
			'dbuser' => 'XXX2',
			'dbname' => 'XXXXX2',
			'dbpass' => '',
			'prefix' => 'blah_2',
		),
		array(
			'dbhost' => 'localhost3',
			'dbuser' => 'XXX3',
			'dbname' => 'XXXXX3',
			'dbpass' => '',
			'prefix' => 'blah_3',
		),
);

#
#	then loop the array to check the databases
#	and set it so that if one returns false we get a warning...
#
foreach ($array as $host => $h)
{
	$x = chk_db( $h['dbhost'], $h['dbname'], $h['dbuser'], $h['dbpass'], $h['prefix']);
}
echo $messages;
$message = wordwrap($messages, 70);

// Send
mail('[email protected]', 'Db Status', $message);

 

this prints it to the screen and emails a copy as well... also will say if the database in the host is active or not...

 

hope this helps...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.