Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

postgresql - PHP and Postgres: catching errors?

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 )
    );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...