DB2 10.5 for Linux, UNIX, and Windows

Error-handling functions in PHP applications (ibm_db2)

Sometimes errors happen when you attempt to connect to a database or issue an SQL statement. The username or password might be incorrect, a table or column name might be misspelled, or the SQL statement might be invalid. The ibm_db2 API provides error-handling functions to help you recover gracefully from the error situations.

Connection errors

Use one of the listed functions to retrieve diagnostic information if a connection attempt fails.

Table 1. ibm_db2 functions for handling connection errors
Function Description
db2_conn_error Retrieves the SQLSTATE returned by the last connection attempt
db2_conn_errormsg Retrieves a descriptive error message appropriate for an application error log

SQL errors

Use one of the listed functions to retrieve diagnostic information if an attempt to prepare or execute an SQL statement or to fetch a result from a result set fails.

Table 2. ibm_db2 functions for handling SQL errors
Function Description
db2_stmt_error Retrieves the SQLSTATE returned by the last attempt to prepare or execute an SQL statement or to fetch a result from a result set
db2_stmt_errormsg Retrieves a descriptive error message appropriate for an application error log

For more information about the ibm_db2 API, see http://www.php.net/docs.php.

Tip: To avoid security vulnerabilities that might result from directly displaying the raw SQLSTATE returned from the database, and to offer a better overall user experience in your web application, use a switch structure to recover from known error states or return custom error messages. For example:
switch($this->state):
    case '22001':
        // More data than allowed for the defined column
        $message = "You entered too many characters for this value.";
        break;

Example

Example 1: Handle connection errors

$connection = db2_connect($database, $user, $password);
if (!$connection) {
    $this->state = db2_conn_error();
    return false;
}

Example 2: Handle SQL errors

$stmt = db2_prepare($connection, "DELETE FROM employee 
WHERE firstnme = ?");
if (!$stmt) {
    $this->state = db2_stmt_error();
    return false;
}

Example 3: Handle SQL errors that result from executing prepared statements

$success = db2_execute($stmt, array('Dan');
if (!$success) {
    $this->state = db2_stmt_error($stmt);
    return $false;
}