PDA

View Full Version : Mysql_error mail system admin


Trinity-Links
11-16-2008, 11:34 AM
During the build of my website I used mysql_error() to point out my failings to then rectify.

This code will log errors and email me with them once the website has gone live :

<?php
$b_debugmode = 1; // 0 || 1

$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';

function db_query( $query ){
global $b_debugmode;

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
if($b_debugmode){
$message = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
$message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
die($message);
}

raise_error('db_query_error: ' . $message);
}
return $result;
}

function raise_error( $message ){
global $system_operator_mail, $system_from_mail;

$serror=
"Env: " . $_SERVER['SERVER_NAME'] . "\r\n" .
"timestamp: " . Date('m/d/Y H:i:s') . "\r\n" .
"script: " . $_SERVER['PHP_SELF'] . "\r\n" .
"error: " . $message ."\r\n\r\n";

// open a log file and write error
$fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
if($fhandle){
fwrite( $fhandle, $serror );
fclose(( $fhandle ));
}

// e-mail error to system operator
if(!$b_debugmode)
mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
}

?>

Rather than pasting this script after every $query
is there a way of creating a generic error detection which will log and email what ever the problem...... its either that or I'm going to have to get my pasting shoes on!
:thumbsup:

Fumigator
11-17-2008, 07:23 PM
Why not just call a function after every query that decides how to handle an error?

Also instead of a global variable that handles what debug mode you are in, you could use a constant, which is automatically global so you don't need to declare it as global in every function.

http://us.php.net/manual/en/language.constants.php



//somewhere in a config file somewhere, define the RUN_MODE constant
define("RUN_MODE", "test");

.
.
.

//in your application scripts
$query = "SELECT * FROM table";
$result = mysql_query($query);
checkQueryResults($result);

.
.
.

//in your functions script
function checkQueryResults($result) {
if (!$result) {
if (RUN_MODE == "test") {
//display error, etc
} else {
//log and email error
}
}
}

Trinity-Links
11-26-2008, 07:15 PM
cheers bud.... very helpfull