Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you prepare and execute using `try` and `catch` using PDO?

Tags:

exception

php

pdo

I have been using PDO for a couple of years now but I have never fully researched when you should prepare and execute using try and catch.

My understanding is that you should use try and catch when data may contain user input.

So this code for example is safe:

public function getDetails($filename, $what){
    $query = $this->handler->prepare('SELECT * FROM videos WHERE v_fileName = :v_fileName');
    try{
        $query->execute([
            ':v_fileName' => $filename
        ]);
    }catch(PDOException $e){
        return $e->getMessage();
    }
}

$filename in this example is something which comes from the URL.

When not getting anything from the URL for example like this it is also completely save:

$query = $this->handler->prepare('SELECT * FROM videos WHERE u_id = :u_id ORDER BY v_id LIMIT :climit,1');
$query->execute([
    ':u_id'     => $this->user->getChannelId($userid),
    ':climit'   => $optional[1]
]);

$fetch = $query->fetch(PDO::FETCH_ASSOC);

Is my understanding of preparing statements correct and if not, how should I do it?

like image 992
Tom Avatar asked Apr 23 '26 15:04

Tom


1 Answers

Only when you have a very good reason to do so.

This doesn't apply to only PDO exceptions. The same goes for any exception. Only catch the exception if your code can recover from it and perform some other action instead.

Catching exceptions just to echo or return $e->getMessage(); is not a valid reason. Your code doesn't recover from the problem, you are just handicapping the exception.

A good example of when you might want to recover is if you are using database transactions and in case of failure, you want to rollback and do something else. You can call PDO::rollBack() in your catch and then make your code perform some alternative logic.

Try-catch is not a security measure. It has nothing to do with user input. It is used only in situations when you expect your code to fail, but you have a plan B to handle the situation.

For more information, you can read My PDO Statement doesn't work and the article PHP error reporting

like image 143
Dharman Avatar answered Apr 26 '26 04:04

Dharman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!