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 usingtry
andcatch
.
My understanding is that you should usetry
andcatch
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?
Answer
Solution:
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 toecho
orreturn $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 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
Answer
Solution:
Is my understanding of preparing statements correct and if not, how should I do it?
You use prepared statement to avoid SQL INJECTION. Prepared statements will quote the parameters to avoid it.
My understanding is that you should use try and catch when data may contain user input
Thetry
catch
block is used to handle erros in your application, not really related to prepared statements.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: please make sure the php redis extension is installed and enabled.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.