【发布时间】:2012-06-17 21:03:10
【问题描述】:
所以我正在学习 PDO,并从标准的 PHP MySQL 函数进行转换。但是,我有一个问题。关于try {} 块,它们到底应该在里面,什么应该在外面?
所有使用$sth-> ... 的东西都应该在try {} 里面吗?它应该只是从语句第一次准备到执行的时候吗?比这还少?
任何帮助将不胜感激。 :)
这是我在课堂上的一个示例方法。组织得当吗?请注意我是如何将 everything 放入 try {} 的。那是错的吗?对我来说感觉不正确,但我不知道我应该如何改变它。
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);
}
}
【问题讨论】:
-
前几天我也在工作中问同样的问题!一切顺利吗?
-
非常好的问题。很多开发人员都不知道这个主题