3

I am converting a PHP script from MySQL to PostgreSQL.

I thought the equivalent for mysqli_errno is pg_last_error, is it okay? If not, could you please suggest an alternative?

2 Answers 2

3

You're correct. You can use pg_last_error() to get the last error for the connection.

Example:

pg_connect(...) or die('Could not connect: ' . pg_last_error());
Sign up to request clarification or add additional context in comments.

Comments

1

I disagree with Francois Deschene's answer.

Unfortunately, the pg API seems a bit weaker than the MySQLi API. I've considered using PDO, but I haven't looked too into that yet.

To answer your question, you'll have to go somewhat out of the way to get the equivalent to "mysqli_errno" (that is, the actual error number). pg_last_error() returns a string, not a number. And numbers are a bit easier to deal with.

http://www.postgresql.org/docs/8.1/static/errcodes-appendix.html

Anyway, to get the error NUMBER, you'll have to use a combination of functions.

pg_send_query_params(blah blah); // or pg_send_query() if you don't use prepared statements
$result = pg_get_result($connection);
$result_status = pg_result_status($result);
$mysqli_errno_equivalent = pg_result_error_field($result_status, PGSQL_DIAG_SQLSTATE);

Hopefully, someone else will come up with a easier solution. But this is what I've been using in my code (because the error numbers in PostgreSQL Appendix A are much easier to deal with than the full text error strings).

Fortunately, it is trivial to write a simple wrapper around this so you don't repeat yourself over and over again.

The documentation seems to imply that this is the best way to get the number. http://www.php.net/manual/en/function.pg-result-error-field.php

1 Comment

The PostgreSQL protocol supports an extensive error report breakdown, the PHP driver (at least at the time this was written) just doesn't offer a way to access it.

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.