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
- To catch a PDOException object and handle the associated
error:
- Wrap the call to the PDO constructor in a try block.
- Following the try block, include a catch block
that catches the PDOException object.
- Retrieve the error message associated with the error
by invoking the Exception::getMessage method on
the PDOException object.
- To retrieve the SQLSTATE associated with a PDO or PDOStatement
object, invoke the errorCode method on the object.
- 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.