postgresql PHP 和 Postgres:捕捉错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1375331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP and Postgres: catching errors?
提问by hhh
How should I prepare the code if it something fails? With try-catch statement or?
如果出现问题,我应该如何准备代码?用 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 = ',
array ( $question_id )
);
回答by Anti Veeranna
If you want exceptions, then you need to use PDO.
如果你想要例外,那么你需要使用 PDO。
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_* 函数和您的代码的情况下,您需要检查 $result 是否具有 false 值,如果是,则发生错误。
You can get the error description with pg_last_error()
您可以使用 pg_last_error() 获取错误描述
Something like this:
像这样的东西:
$result = pg_query_params ( $dbconn,
'DELETE FROM questions
WHERE question_id = ',
array ( $question_id )
);
if ($result === false) {
print pg_last_error($dbconn);
} else {
print 'everything was ok';
}
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.
因此,基本上,每次使用 pg_* 函数时,都需要检查是否返回了 false,这些函数就是这样。
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.
是的,您可以构建自己的包装器,因此您可以调用 my_db_query() 而不是 pg_query*,然后它会执行返回值检查和异常抛出。
Or, you could go with PDO, which is able to throw you PDOException for all the errors that can occour.
或者,您可以使用 PDO,它能够针对可能出现的所有错误向您抛出 PDOException。
回答by Ann
I have another practice
我还有一个练习
$result = pg_query_params ( $dbconn,'DELETE FROM questions WHERE question_id = ', array ( $question_id ) )
or die(pg_last_error($dbconn));