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
151 views
in Technique[技术] by (71.8m points)

php - When should you prepare and execute using `try` and `catch` using 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?

question from:https://stackoverflow.com/questions/65943333/when-should-you-prepare-and-execute-using-try-and-catch-using-pdo

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

1 Reply

0 votes
by (71.8m points)

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


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

...