PHP and Postgres: catching errors?(PHP 和 Postgres:捕捉错误?)
问题描述
如果代码失败,我应该如何准备代码?使用 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:捕捉错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 和 Postgres:捕捉错误?


基础教程推荐
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01