How to handle errors in MySQL using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to handle errors in MySQL using PHP

Post by Tony » Sun Nov 29, 2009 5:04 am

Would you like to be notified when your site has a MySQL error? This PHP script will trap MySQL errors and send the user a custom error page. It will then either log the error or email you with the details of the error, or both. You can customize this example to launch other pages based on the type of error, or to have the error routine do what ever you want.

A typical MySQL statement should look like this:

Code: Select all

<?php 
mysql_connect("$host", "$dbuser", "$dbpswd") or sql_error("connect",mysql_error()); 
?>
When there is an error, this will call the function sql_error, sending a marker (in this case "connect") and the actual MySQL error.

At the top of your script (before any MySQL statements) put the function sql_error:

Code: Select all

<?php
function sql_error($function,$mysql_err) {
  /*
  This script can send an email and/or make an entry in a log file
  There are two variables below - one for an email address and one for a log file
  Set both vraiables to the values you want to use
  If you do not want either an email or log entry, comment out the respective line
  For example, if you do not want an email sent, put a // in front of the $emailAddress line - same for the $logFile line
  */
  $logFile = $_SERVER['DOCUMENT_ROOT'].'/mysql.log';   // full path to your log file - you should create an empty starter file if you use logging
  $emailAddress = "[email protected]";  // set to your email address
  putenv('TZ=EST5EDT'); // eastern time
  // modify the above values to fit your environment
  echo "<center><br><hr>
  Oops . . . looks like our database is having technical problems.
  <br><br>
  Please come back later . . . hopefully we can get things up and running again soon.
  <hr>";
  if (isset($logFile)) {
    $logData = "Error: $function - $mysql_err"."||".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."||".$_SERVER['REMOTE_ADDR']."||".date('Y-m-d H:i:s')."\r\n";
    @file_put_contents($logFile,$logData,FILE_APPEND|LOCK_EX);
  }
  if (isset($emailAddress)) {
    $error_time = (date(" F d h:ia"));
    $message .= "There has been a MySQL error.\n\n";
    $message .= "Error: $function - $mysql_err\n\n";
    $message .= "Server time of the error: $error_time\n\n";
    mail($emailAddress,"MySQL error",$message,"From: Website <>");
  }
  die();
}
?>
Post Reply

Return to “PHP & MySQL”