wor*_*wer 5 php sql postgresql error-handling
我想捕捉并使用php显示网页上的查询错误(以我选择的方式).所以代替下面的代码
$result=pg_query($connection,$query);
if($result){
//success
}
else{
echo pg_last_error($connection);
}
Run Code Online (Sandbox Code Playgroud)
我可以使用像错误代码匹配或其他方法来实现类似的方法
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"
}
Run Code Online (Sandbox Code Playgroud)
注意我正在使用postgresql
Dan*_*ité 12
可以检索所需的标准SQLSTATE错误代码,但有一个技巧:查询必须通过异步pg_send_query()而不是同步发送pg_query().这是因为错误pg_query()返回false而不是查看错误详细信息所需的资源.
当调用pg_get_result()之后pg_send_query,它将一直阻塞,直到查询完成,因此与同步情况相比,它并没有真正复杂化.它返回一个结果,可以充分利用该结果进行精确的错误处理.
例:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您应该解析返回的信息pg_last_error以了解错误类型。所以我会这样:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13812 次 |
| 最近记录: |