在PHP中捕获postgres错误

时间:2010-07-12 14:27:42

标签: php postgresql

我在postgressql中使用primare key(pk_user)。如果我插入了错误的参数。

postgres调用异常:(错误:重复键值违反了唯一约束“pk_user”)

这没关系,但我喜欢抓住这个错误并将其转换为用户界面(使用此用户名)

我的php脚本:

$sql="INSERT INTO user (....) VALUES (....)"
@$result=pg_query($dbconn,$sql);
if(!$result) {
 $error= pg_last_error($dbconn);
 if($error==='ERROR: duplicate key value violates unique constraint "pk_user"')
   $outputmesage="this username is used";
....
}
else {
.....
}

但是构造if($error==='ERROR: duplicate key value violates unique constraint "pk_user"') 是错的。我不知道是什么写的。函数strcmp(str1,str2)也是错误的。

P.S: 我很抱歉我的英语不好

2 个答案:

答案 0 :(得分:2)

您可以使用pg_result_error_field但是必须使用pg_send_querypg_get_result(而不是pg_query及其更好的替代pg_query_params):

pg_send_query($dbconn,$sql);
$res = pg_get_result($dbconn);

# check for "UNIQUE VIOLATION"
if(pg_result_error_field($res,PGSQL_DIAG_SQLSTATE) == '23505') {
    ...

另一种方法是使用PDO,将错误处理设置为“ERRMODE_EXCEPTION”,处理异常并查看exception's code属性(同样应该包含SQLSTATE错误代码。

答案 1 :(得分:0)

在插入之前选择此用户名并解决问题。

但如果您尝试最小化对db的查询数量,您可以继续使用您的解决方案,只需将条件更改为这样:

if(strstr($error,"duplicate key value")) {
   $outputmesage="this username is used"; 
}

希望它会有所帮助