PHP和Postgres:捕捉错误? [英] PHP and Postgres: catching errors?

查看:141
本文介绍了PHP和Postgres:捕捉错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果失败,我应该如何准备代码?使用try-catch语句或?

  function delete_question($ question_id){
$ dbconn = pg_connect (host = localhost port = 5432 dbname = heoa user = heoa password = 123);

//删除问题及其依赖关系:答案和标签
$ result = pg_query_params($ dbconn,
'DELETE FROM questions
WHERE question_id = $ 1',
数组($ question_id)
);


解决方案

如果你想要异常,那么你需要使用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 {
打印一切都OK;
}

所以,基本上每次使用pg_ *函数时,检查是否返回false,这就是这些函数的方式。



是的,您可以构建自己的包装器,而不是pg_query *,您调用my_db_query()然后它执行返回值检查和异常抛出。



或者,您可以使用PDO,它可以抛出您可能发生的所有错误的PDOException。 / p>

How should I prepare the code if it something fails? With try-catch statement or?

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 )
    );

解决方案

If you want exceptions, then you need to use 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.

You can get the error description with pg_last_error()

Something like this:

$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';
}

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.

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.

Or, you could go with PDO, which is able to throw you PDOException for all the errors that can occour.

这篇关于PHP和Postgres:捕捉错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆