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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…