catching errors from Postgresql to PHP

It's possible to retrieve the desirable standard SQLSTATE errcode, but there's a trick: the query has to be sent through the asynchronous pg_send_query() instead of the synchronous pg_query(). This is because pg_query() returns false on error instead of the resource that is required to peek at the error details.

When pg_get_result() is called after pg_send_query, it will block anyway until the query is done, so it does not really complicate things compared to the synchronous case. And it returns a result which can be fully exploited for precise error handling.

Example:

if (pg_send_query($db, $query)) {
  $res=pg_get_result($db);
  if ($res) {
    $state = pg_result_error_field($res, PGSQL_DIAG_SQLSTATE);
    if ($state==0) {
      // success
    }
    else {
      // some error happened
      if ($state=="23505") { // unique_violation
        // process specific error
      }
      else {
       // process other errors
      }
    }
  }  
}

Also, if the argument passed to pg_query might contain several SQL statements (separated by semicolons), the above example should be extended to retrieve all results in a loop, as mentioned in the comment by @user1760150. Compared to pg_query which returns only the last result, pg_get_result in a loop gives access to the results of each statement of the combined query.


You should parse the return of pg_last_error to know the type of error. So I would go to sth like this :

$result = pg_query($connection,$query);

if($result)
{
  //success
}
else
{
  $error = pg_last_error($connection);

  // you need to adapt this regex
  if (preg_match('/duplicate/i', $error))
  {
    echo "this value already exists";
  }
  // you need to adapt this regex
  elseif(preg_match('/different type/i', $error))
  {
    echo "You should enter wrong type for column blabla"
  }
  else
  {
    // different error
  }
}

You can get access to SQLSTATE through the two main drivers.

http://uk3.php.net/manual/en/function.pg-result-error-field.php

http://www.php.net/manual/en/pdo.errorcode.php