PHP and Postgres: catching errors?

前端 未结 2 1766
萌比男神i
萌比男神i 2020-12-11 21:38

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

function delete_question ( $question_id ) {
    $dbconn =          


        
相关标签:
2条回答
  • 2020-12-11 22:13

    I have another practice

    $result = pg_query_params ( $dbconn,'DELETE FROM questions WHERE question_id = $1', array ( $question_id ) )
              or die(pg_last_error($dbconn));
    
    0 讨论(0)
  • 2020-12-11 22:14

    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.

    0 讨论(0)
提交回复
热议问题