2012-09-10 33 views
3

我想捕捉並顯示使用php的網頁上的查詢錯誤(以我選擇的方式)。因此,而不是下面從Postgresql捕獲錯誤到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

+0

是的,你可以這樣做,但我不知道你在問什麼。 –

+0

@AleksG 我不想使用pg_last_error函數。我想爲相應的錯誤手動編寫錯誤消息 – woryzower

回答

7

這是可能的檢索要求標準SQLSTATE ERRCODE,但有一招:查詢已通過異步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 
     } 
    } 
    } 
} 
1

你應該分析返回的代碼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 
    } 
} 
+0

Logical.But沒有更高效或內置的方式,如果(錯誤代碼== errorcodeof(duplicate_key) - >做某事 – woryzower

+1

或許,但看看一個[這個評論](http://www.php.net/manual/fr/function.pg-last-error.php#99626)在php.net上。這個人通過執行'stripos'來執行'檢測到死鎖'但我同意,如果你可以直接檢索代碼錯誤,它可以更有效率。 – j0k

+0

Yick。面對I18N和翻譯是否安全?你不能從PHP獲取'SQLSTATE'並使用它這是最正確的做法 –