Error Handling: Throwing PHP exceptions with the mysql_* extension.

Unfortunately, the (outdated) mysql_* extension in PHP does not support exception handling.
Obviously, this is an issue for those of us who want to avail of the flexibility that exceptions can offer. For the most part, developers who use the mysql_* extension tend to carry out their “error handling” like so:

mysql_query($sql, $connection) or die(mysql_error($connection));

The problem with this approach is that the rest of our application is completely oblivious to any SQL errors that may occur. If the query fails, the script is halted and there is no way to recover. To make matters even worse, the user will be presented with a nasty-looking SQL error.

A better, more-flexible approach would be to throw an exception if the query fails:

$result = mysql_query($sql, $connection);
if($result === false){
    throw new Exception(mysql_error($connection));

The code above checks to see if mysql_query returns a boolean FALSE value. If it does, we assume that an error has occurred. If an error has occurred, we proceed to throw an Exception containing the MySQL error message.

If you’re worried about the extra added code, then you can abstract your exception-throwing into a custom function like so:

function query($sql, $conn = null){
    $res = mysql_query($sql, $conn);
    if($res === false){
        throw new Exception(mysql_error($conn));
    return $res;

Using this custom function, we can execute our queries like so (and catch any errors):

    query("SELECT name FROM users", $connection);
} catch(Exception $e){

Using exceptions can be extremely beneficial when it comes to handling failed SQL queries.
In the vast majority of cases, a failed SQL query indicates that the application is down and that something has gone terribly wrong. In cases like this, shouldn’t catch the exception in question. Instead, you should “handle” it via a custom exception handler. This can be achieved with the function set_exception_handler. An example:

function app_error($exception) {
    header("HTTP/1.1 500 Internal Server Error");
    include 'template/error.html';

Basically, whenever an exception is thrown, our application will automatically call the app_error function above. There, we can log the error, set a 500 internal server error header and provide the user with a custom “error template”.