PHP和Postgres:捕获错误?

时间:2009-09-03 19:06:50

标签: 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 )
    );

2 个答案:

答案 0 :(得分:8)

如果您需要例外,则需要使用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';
}

所以,基本上,每次使用pg_ *函数时,都需要检查是否返回了false,这就是这些函数的用法。

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

或者,你可以使用PDO,它可以为你发现的所有错误抛出PDOException。

答案 1 :(得分:0)

我有另一种做法

$result = pg_query_params ( $dbconn,'DELETE FROM questions WHERE question_id = $1', array ( $question_id ) )
          or die(pg_last_error($dbconn));