DB2 10.5 for Linux, UNIX, and Windows

Handling errors and warnings in PHP (PDO)

Sometimes errors happen when you attempt to connect to a database or issue an SQL statement. The password for your connection might be incorrect, a table you referred to in a SELECT statement might not exist, or the SQL statement might be invalid. PDO provides error-handling methods to help you recover gracefully from the error situations.

Before you begin

You must set up the PHP environment on your system and enable the PDO and PDO_IBM extensions.

About this task

PDO gives you the option of handling errors as warnings, errors, or exceptions. However, when you create a new PDO connection object, PDO always throws a PDOException object if an error occurs. If you do not catch the exception, PHP prints a backtrace of the error information that might expose your database connection credentials, including your user name and password.

This procedure catches a PDOException object and handles the associated error.

Procedure

  1. To catch a PDOException object and handle the associated error:
    1. Wrap the call to the PDO constructor in a try block.
    2. Following the try block, include a catch block that catches the PDOException object.
    3. Retrieve the error message associated with the error by invoking the Exception::getMessage method on the PDOException object.
  2. To retrieve the SQLSTATE associated with a PDO or PDOStatement object, invoke the errorCode method on the object.
  3. To retrieve an array of error information associated with a PDO or PDOStatement object, invoke the errorInfo method on the object. The array contains a string representing the SQLSTATE as the first element, an integer representing the SQL or CLI error code as the second element, and a string containing the full text error message as the third element.

    For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.