So I'm working on learning PDO, and making the transfer from the standard PHP MySQL functions. However, I have a question. Regarding the try {}
blocks, what exactly should be in them, and what should go outside it?
Should everything that uses $sth-> ...
be inside try {}
? Should it just be from when the statement is first prepared all the way to when it is executed? Even less than that?
Any help would be greatly appreciated. :)
Here is an example method I have in a class. Is it organized properly? Notice how I put everything inside try {}
. Is that wrong? It feels incorrect to me, but I'm not sure how I should change it.
protected function authorized()
{
try
{
// Attempt to grab the user from the database.
$sth = $dbh->prepare("
SELECT COUNT(*) AS num_rows
FROM users
WHERE user_id = :user_id
");
$sth->bindParam(':user_id', $this->user_id);
$sth->execute();
// Check if user exists in database.
if ($sth->fetch()->num_rows > 0)
{
// User exists in database, and is therefore valid.
return TRUE;
}
else
{
// User does not exist in database, and is therefore invalid.
return FALSE;
}
}
catch (PDOException $e)
{
pdo_error($e);
}
}