Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching errors from Postgresql to PHP

I want to catch and show the error(in a way that i choose) of a query on the web page using php . So instead of the code below

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

if($result){
    //success

}
else{
    echo pg_last_error($connection);
}

can i use a method like error code matching or something else to achieve things like

if(error equals duplicate value error){
 echo "this value already exists";
}
else if(error equals different type error){
 echo "You should enter wrong type for column blabla"
}

Note I am using postgresql

like image 285
woryzower Avatar asked Sep 10 '12 09:09

woryzower


3 Answers

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.

like image 128
Daniel Vérité Avatar answered Sep 18 '22 18:09

Daniel Vérité


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
  }
}
like image 40
j0k Avatar answered Sep 19 '22 18:09

j0k


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

like image 26
Richard Huxton Avatar answered Sep 19 '22 18:09

Richard Huxton