hhh*_*hhh 4 php postgresql error-handling
如果某些内容失败,我该如何准备代码呢?用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 )
);
Run Code Online (Sandbox Code Playgroud)
如果您想要例外,那么您需要使用PDO.
在pg_*函数和您的代码的情况下,您需要检查$ result是否具有false值,如果是,则发生错误.
你可以用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';
}
Run Code Online (Sandbox Code Playgroud)
所以,基本上,每次使用pg_*函数时,都需要检查是否返回了false,这就是它们与这些函数的关系.
是的,您可以构建自己的包装器,而不是pg_query*,而是调用my_db_query(),然后执行返回值检查和异常抛出.
或者,你可以使用PDO,它可以为你发现的所有错误抛出PDOException.