捕获从Postgresql到PHP的错误 [英] catching errors from Postgresql to PHP
问题描述
我想使用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"
}
注意我正在使用postgresql
Note I am using postgresql
推荐答案
检索所需的标准 SQLSTATE errcode,但有一个技巧:查询必须通过异步 pg_send_query()而不是同步的 pg_query()
。这是因为 pg_query()
返回 false
而不是窥视错误详细信息所需的资源。
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.
当 pg_get_result()在 pg_send_query
后调用,它将阻塞,直到查询完成,因此与同步情况相比,并不会使事情复杂化。
它返回一个可以被完全利用来进行精确错误处理的结果。
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.
示例:
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
}
}
}
}
这篇关于捕获从Postgresql到PHP的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!