問題描述
如果代碼失敗,我應該如何準備代碼?使用 try-catch 語句還是?
function delete_question ( $question_id ) {
$dbconn = pg_connect("host=localhost port=5432 dbname=heoa user=heoa password=123");
// removes questions and its dependencies: answers and tags
$result = pg_query_params ( $dbconn,
'DELETE FROM questions
WHERE question_id = $1',
array ( $question_id )
);
推薦答案
如果你想要異常,那么你需要使用 PDO.
If you want exceptions, then you need to use PDO.
對于 pg_* 函數和您的代碼,您需要檢查 $result 是否具有 false 值,如果是,則發生錯誤.
in case of pg_* functions and your code, you need to check whether $result has the value of false, if it does, then an error occured.
您可以使用 pg_last_error() 獲取錯誤描述
You can get the error description with pg_last_error()
像這樣:
$result = pg_query_params ( $dbconn,
'DELETE FROM questions
WHERE question_id = $1',
array ( $question_id )
);
if ($result === false) {
print pg_last_error($dbconn);
} else {
print 'everything was ok';
}
所以,基本上,每次使用 pg_* 函數時,都需要檢查是否返回了 false,這些函數就是這樣.
So, basically, every time you use a pg_* function, you need to check whether false was returned, that's just the way it is with those functions.
是的,您可以構建自己的包裝器,因此您可以調用 my_db_query() 而不是 pg_query*,然后它會執行返回值檢查和異常拋出.
Yes, you can build your own wrappers so instead of pg_query* you call my_db_query(), which then does the return value checking and exception throwing.
或者,您可以使用 PDO,它可以針對可能出現的所有錯誤向您拋出 PDOException.
Or, you could go with PDO, which is able to throw you PDOException for all the errors that can occour.
這篇關于PHP 和 Postgres:捕捉錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!