我想在使用php的网页上捕捉并显示查询的错误(以我选择的方式)。所以不是下面的代码
$result=pg_query($connection,$query);
if($result){
//success
}
else{
echo pg_last_error($connection);
}
我能用错误代码匹配之类的方法或其他方法来实现之类的功能吗
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
可以检索所需的标准SQLSTATE错误代码,但有一个技巧:必须通过异步pg_send_query()而不是同步pg_query()
发送查询。这是因为pg_query()
在出错时返回false
,而不是查看错误详细信息所需的资源。
当在pg_send_query
之后调用pg_get_result()时,它无论如何都会阻塞,直到查询完成,因此与同步情况相比,它不会真正使事情复杂化。它返回一个结果,可以充分利用该结果进行精确的错误处理。
示例:
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
}
}
}
}
此外,如果传递给pg_query
的参数可能包含多个SQL语句(用分号分隔),则应扩展上述示例以检索循环中的所有结果,如@user1760150在注释中所述。与只返回最后一个结果的pg_query
相比,循环中的pg_get_result
可以访问组合查询的每个语句的结果。
您应该解析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
}
}
您可以通过两个主要驱动程序访问SQLSTATE。
http://uk3.php.net/manual/en/function.pg-result-error-field.php
http://www.php.net/manual/en/pdo.errorcode.php