0

I thought all the pg_* functions return false on error and it is your job to check it. However, as indicated below, my server is outputting an error message to the PHP log. How can I prevent this from happening because I obviously don't want these messages polluting the log as I deal with these kind of exceptions by checking the query result object's error code.

Warning: pg_query_params(): Query failed: ERROR: duplicate key value violates unique constraint "email" DETAIL: Key (email)=([email protected]) already exists. in /xxx.php on line 100

1 Answer 1

2

From the point of view of PHP, there are at least two ways to avoid the error message, one that is "quick and dirty", and the other one more complicated but clean.

Solution #1: add a @ sign before the call to mute any error message

@pg_query_params($db, $query, $params);

The drawback is that there'll be no log whatever the reason of the failure.

Solution #2: use pg_send_query_params(), process the error code, check that it is an expected error and ignore it only in this case, otherwise raise the error. Sample code:

if (pg_send_query_params($db, $query, $params)) {
  $res=pg_get_result($db);
  if ($res) {
    $state = pg_result_error_field($res, PGSQL_DIAG_SQLSTATE);
    if ($state==0) {
      // success
    }
    else {
      // an error happened
      if ($state=="23505") { // unique_violation
        // process or ignore expected error
      }
      else {
        // process other errors
        trigger_error (pg_last_error(), E_USER_ERROR);  
      }
    }
  }  
}
else { 
 trigger_error ("pg_send_query_params failed:".pg_last_error(), E_USER_ERROR);
}

In both cases, there will be a trace of the error in the PostgreSQL error log unless you've muted it there too, but that's a separate problem that is generally solved by using a server-side INSERT with error trapping in procedural code rather than client-side.

Sign up to request clarification or add additional context in comments.

3 Comments

@ sign is a neat trick but my point was that I was doing Solution #2 but it was still sending an error to log regardless.
@sevado: pg_query_params will output the error, but not pg_send_query_params as I suggest.
Ah. Totally missed that. I did switch to pg_send_query so I could use pg_result_error but I forgot to check if that function also outputs to log but you just answered that question. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.