Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 )
    );
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
 
You mean I could catch pg_last_error without explicit throw-statement? –  hhh Sep 3 '09 at 19:12
 
More about the function: us.php.net/manual/en/function.pg-last-error.php –  hhh Sep 3 '09 at 19:13
1  
You can always wrap your own exceptions around the pg_* functions. –  Frank Farmer Sep 3 '09 at 19:13
 
like? pastebin.com/m3feb612b –  hhh Sep 3 '09 at 19:31
1  
You don't really need the 'else' in the if-else, since throwing an exception will break you out of the function. –  nilamo Sep 3 '09 at 19:38
show 3 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.