Try catch mysql query php

Elaborating on yasaluyari's answer I would stick with something like this:

We can just modify our mysql_query as follows:

function mysql_catchquery($query,$emsg='Error submitting the query'){
    if ($result=mysql_query($query)) return $result;
    else throw new Exception($emsg);
}

Now we can simply use it like this, some good example:

try {
    mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
    mysql_catchquery('insert into a values(666),(418),(93)');
    mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
    $result=mysql_catchquery('select * from d where ID=7777777');
    while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
    echo $e->getMessage();
}

Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.

Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.

When PHP version 5 was released, it incorporated a built-in model to catch errors and exceptions. Handling errors in PHP with try catch blocks is almost the same as handling errors in other programming languages.

When a PHP exception is thrown, the PHP runtime looks for a catch statement that can handle that type of exception. It will continue checking the calling methods up the stack trace until a catch statement is found. If one is not found, the exception is handed to the global exception handler that we will also cover in this article.

Simple PHP try catch example

Here is an example of a basic PHP try catch statement.

try {
    // run your code here
}
catch (exception $e) {
    //code to handle the exception
}
finally {
    //optional code that always runs
}

PHP error handling keywords

The following keywords are used for PHP exception handling.

  • Try: The try block contains the code that may potentially throw an exception. All of the code within the try block is executed until an exception is potentially thrown.
  • Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception.
  • Catch: This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown.
  • Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. This is useful for scenarios like closing a database connection regardless if an exception occurred or not.

PHP try catch with multiple exception types

PHP supports using multiple catch blocks within try catch. This allows us to customize our code based on the type of exception that was thrown. This is useful for customizing how you display an error message to a user, or if you should potentially retry something that failed the first time.

try {
    // run your code here
}
catch (Exception $e) {
    echo $e->getMessage();
}
catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}

When to use try catch-finally

In PHP version 5.5, the finally block was added. Sometimes in your PHP error handling code, you will also want to use a finally section. Finally is useful for more than just exception handling, it is used to perform cleanup code such as closing a file, closing a database connection, etc.

The finally block always executes when the try catch block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Example for try catch-finally:

try {
    print "this is our try block n";
    throw new Exception();
} catch (Exception $e) {
    print "something went wrong, caught yah! n";
} finally {
    print "this part is always executed n";
}

Below is the diagram showing how the program works.

Try catch mysql query php

Creating custom PHP exception types

PHP also allows creating custom exception types.This can be useful for creating custom exceptions in your application that you can have special exception handling around.

To create a custom exception handler, we must create a special class with functions that can be called when an exception occurs. The class must be an extension of the exception class.

class DivideByZeroException extends Exception {};

The custom exception class inherits the properties from PHP’s Exception class and you can add custom functions to it. You may not want to display all the details of an exception to the user or you can display a user-friendly message and log the error message internally for monitoring.

The sample below uses a custom PHP exception with multiple catch statements.

class DivideByZeroException extends Exception {};
class DivideByNegativeException extends Exception {};

function process_divide($denominator)
{
    try
    {
        if ($denominator == 0)
        {
            throw new DivideByZeroException();
        }
        else if ($denominator < 0)
        {
            throw new DivideByNegativeException();
        }
        else
        {
            echo 100 / $denominator;
        }
    }
    catch (DivideByZeroException $ex)
    {
        echo "Divide by zero exception!";
    }
    catch (DivideByNegativeException $ex)
    {
        echo "Divide by negative number exception!";
    }
    catch (Exception $x)
    {
        echo "UNKNOWN EXCEPTION!";
    }
}

The code above throws an exception and catches it with a custom exception class. The DivideByZeroException() and DivideByNegativeException() classes are created as extensions of the existing Exception class; this way, it inherits all methods and properties from the Exception class. The “try” block is executed and an exception is thrown if the denominator is zero or negative number. The “catch” block catches the exception and displays the error message.

The flowchart below summarizes how our sample code above works for custom types of exceptions.

Try catch mysql query php

Global PHP exception handling

In a perfect world, your code will do proper exception handling. As a best practice, you should also configure a global PHP exception handler. It will be called in case an unhandled exception occurs that was not called in a proper PHP try catch block.

To configure a global PHP exception handler, we will use the set_exception_handler() function to set a user-defined function to handle all uncaught exceptions:

function our_global_exception_handler($exception) {
    //this code should log the exception to disk and an error tracking system
    echo "Exception:" . $exception->getMessage();
}

set_exception_handler(‘our_global_exception_handler’);

How to properly log exceptions in your PHP try catch blocks

Logging is usually the eyes and ears for most developers when it comes to troubleshooting application problems. Logging exceptions so you can find them after they happen is a really important part of PHP error handling best practices.

Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

Error logs are crucial during development because it allows developers to see warnings, errors, notices, etc. that were logged while the application is running. That you can handle them appropriately through the PHP exception handling techniques try catch we just learned.

Depending on the PHP framework you are using, whether Laravel, Codeigniter, Symfony, or others, they may provide built-in logging frameworks. You can also use Monolog, which is a standard PHP logging library. Regardless of the logging framework you are using, you want to always log important exceptions being thrown in your code.

Here is a sample of a try/catch that logs errors with Monolog:

require_once(DIR.'/vendor/autoload.php');
use MonologLogger;
use MonologHandlerStreamHandler;

$logger = new Logger('channel-name');
$logger->pushHandler(new StreamHandler(DIR.'/app.log', Logger::DEBUG));

try {
    // Code does some stuff
    // debug logging statement
    $logger->info('This is a log! ^_^ ');
}
catch (Exception $ex) {
    $logger->error('Oh no an exception happened! ');
}

How to use try catch with MySQL

The PHP libraries for MySQL, PDO, and mysqli, have different modes for error handling. If you do not have exceptions enables for those libraries, you can’t use try catch blocks. This makes error handling different and perhaps more complicated.

PDO

In PDO, you must enable ERRMODE_EXCEPTION when creating the connection.

// connect to MySQL
$conn = new PDO('mysql:host=localhost;dbname=stackifydb;charset=utf8mb4', 'username', 'password');
//PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Learn more about PDO attributes from the PHP docs.

MySQL

For mysqli, you must do something similar:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Learn more from the MySQL docs.

How to view all PHP exceptions in one place

Proper exception handling in PHP is very important. As part of that, you don’t want to simply log your exceptions to a log file and never know they occurred.

The solution is to use an error tracking solution like Stackify’s Retrace. All errors are recorded together with some important details about that error, including the time it occurred, the method that caused it, and the exception type.

Retrace provides many important error tracking and monitoring features. Including the ability to see all except in one place, identifying unique errors, quicking finding new errors after a deployment, email notifications about new errors, and much more.

Stackify’s error and log management tool can help you easily monitor and troubleshoot your application.

Try catch mysql query php

Summary

In this tutorial, we showed how to use PHP try catch blocks. We also covered some advanced uses with multiple exception types and even how to log all of your errors to a logging library. Good error handling best practices are critical to any PHP application. Retrace can help you quickly find and troubleshoot all of the exceptions being thrown in your code.

  • About the Author
  • Latest Posts

How can I get exception from MySQL in PHP?

$db = mysql_select_db('mobile', $conn); mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10'); mysql_close($conn); ....
mysql function are not throwing any exceptions. ... .
Great example, this seems to be the most proper way to do it, and I'm going to stick with it too..

Is there try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

How can I get database error in PHP?

php //Step-1 : Create a database connection $connection=mysql_connect(“localhost”,”root”,”root”); if(! $connection) { die(“Database Connection error” . mysql_error()); } //Step-2 : Select a database to use $db=mysql_select_db(“widget_corp”,$connection); if(!

Can we use try without catch in PHP?

You must use catch with try . Please look php.net manual. PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP.