I'm kinda bored (read "avoiding work") today so I wrote a PHP class to handle errors from MySQL and MS SQL queries. I haven't tested the mysql end of it yet since we only use MS SQL here at work, but here's what I've got so far.. what do you guys think?
<?php
/* =========================================================
Class Name: sql_handler
Date: 05/25/2005
Usage: Query Error Handling and elegant error reporting
Notes: $db: 1 = mssql, 2 = mysql
========================================================= */
class sql_handler
{
var $mail_msg;
var $db_type;
var $query;
var $page;
var $error;
function sql_handler($db, $query, $page)
{
$this->db_type = $db;
$this->query = $query;
$this->page = $page;
}
function treat_mssql_error($buffer)
{
$buffer = ereg_replace("<b>Warning</b>: MS SQL message:","<b>Error in query (SQL Server)</b>: ", $buffer);
$buffer = explode("(severity", $buffer);
return $buffer[0];
}
function run_query()
{
if($this->db_type == 1)
{
ob_start();
$result = mssql_query($this->query);
if(!$result)
{
echo ob_get_contents();
$this->error = $this->treat_mssql_error(ob_get_contents());
ob_end_clean();
$this->mail_msg = "There was an error querying the MS SQL Server on page: " . $this->page . ". An error message has been shown to the user.";
$this->mail_error();
return false;
}
ob_end_clean();
}
else if($this->db_type == 2)
{
$result = mysql_query($this->query);
if(!$result)
{
$this->error = mysql_error();
$this->mail_msg = "There was an error querying the MySQL Server on page: " . $this->page . ". An error message has been shown to the user.";
$this->mail_error();
return false;
}
}
return $result;
}
function mail_error()
{
/* recipients, change to suit */
$to = "bennet.oberholzer@volvo.com";
$subject = "Error Report";
/* HTML mail Content-type header. */
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
/* additional headers */
$headers .= "To: Admin <" . $to . ">, \r\n";
$headers .= "From: DB Server <sqladmin@donotreply.com>\r\n";
/* HTML mail message */
$message = '
<html>
<head>
</head>
<body>
<p style="color:red;font-weight:bold;font-family:Tahoma;font-size:8pt">' . $this->mail_msg . '</p>
<p style="font-family:Tahoma;font-size:8pt">The query was: ' . $this->query . '</p>
<p style="font-family:Tahoma;font-size:8pt">The error was: ' . $this->error . '</p>
</body>
</html>
';
$x = @mail($to, $subject, $message, $headers);
}
}
?>