PHP Function pg_result_error_field()
The php function pg_result_error_field() returns an individual field of the error message associated with a result resource. The function is only available against a PostgreSQL 7.4 or higher server. It can provide more detailed error information than the string returned by pg_last_error(). The error field is identified by a parameter called fieldcode. Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_HINT or PGSQL_DIAG_CONTEXT.
The function is useful when the error message of a failed pg_query() query cannot be determined because it was overwritten by other internal PostgreSQL (libpq) function calls. It is also useful when a database connection is busy or disconnected and it needs to be drained of all results in order to free up resources.
The function pg_result_error_field() is similar to the PQresultErrorField() function introduced in PostgreSQL 7.4. This allows you to get SQLSTATE code from a query, which is far more useful than the error string returned by pg_last_error(). This function uses pg_get_result(), so the result handle must be obtained from a previous call to this function. The function works with PostgreSQL bytea values, so the bytea data must be cast if it is not already in a PHP binary string. This can happen when the client and backend character encoding do not match. For example, when INSERTing a multi-byte string into a table with PostgreSQL 7.2 or later. This is not a problem with older versions of PostgreSQL, which did not support bytea. See the article Using PostgreSQL bytea data with PHP for more information.