In my functions.php I have a set of functions used in my website's page templates. I am wondering what is the best way of handling errors. At the moment, my functions.php looks like this:
// include database
require_once 'system/db.php';
// Functions
// =========
function getUrlsPhotos($db, $resultId) {
$query = "SELECT * FROM pictures WHERE result_id=$resultID ORDER BY id ASC";
$results = $db -> query($query);
// Was there an error?
if ($db -> error) {
$output = 'error_getting_photos';
} else {
// loop for getting photos... ... ...
$output = $array_photos;
}
return $output;
}
function getActivityName($db, $activitiesId) {
$query = "SELECT * FROM activities WHERE id=$activitiesId LIMIT 1";
$results = $db -> query($query);
if ($db -> error) {
$output = 'db_error_getting_activityname';
} else {
$result = $results -> fetch_assoc();
$output = $result;
}
return $output;
}
My goal is to somehow see if an error has occured WITHOUT of course the user seeing it. What is an effective way of handling errors for all my functions? What do I need to initialize?
--- EDIT: ---
Reading more about error handling, I came up with the following script for storing errors in my database:
<?php
function errorHandler($errno, $errstr, $errfile, $errline) {
static $db;
if (empty($db)) {
$db = new PDO(DSN, DBUSER, DBPASS);
}
$query = "INSERT INTO errorlog (severity, message, filename, lineno, time) VALUES (?, ?, ?, ?, NOW())";
$stmt = $db->prepare($query);
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
case E_DEPRECATED:
case E_USER_DEPRECATED:
case E_STRICT:
$stmt->execute(array("NOTICE", $errstr, $errfile, $errline));
break;
case E_WARNING:
case E_USER_WARNING:
$stmt->execute(array("WARNING", $errstr, $errfile, $errline));
break;
case E_ERROR:
case E_USER_ERROR:
$stmt->execute(array("FATAL", $errstr, $errfile, $errline));
exit("FATAL error $errstr at $errfile:$errline");
default:
exit("Unknown error at $errfile:$errline");
}
}
set_error_handler("errorHandler");
My questions:
- What is the best place to put this error handling function in order to be valid for all my php functions? Is it sufficient to put it at the beginning of my functions.php?
- A disadvantage of this solution surely is that there is no way to get notified if the database is down. How can I achieve that in this case I for example get a notification e-mail?