【发布时间】:2016-08-08 17:25:36
【问题描述】:
我怀疑准备好的语句应该在 try/catch 块内部还是外部。
(这是我的 User 类的示例方法)
我应该这样做吗?
public function getEmail( $id_user ) {
$this->_sql = 'SELECT Email FROM '.TBL_USERS.' WHERE IdUser = :id_user';
$stmt = $this->_db->prepare($this->_sql);
try {
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchObject();
if (is_object($row)) {
return $row->Email;
}
return NULL;
} catch (PDOException $e) {
throw $e;
}
}
还是这个?
public function getEmail( $id_user ) {
$this->_sql = 'SELECT Email FROM '.TBL_USERS.' WHERE IdUser = :id_user';
try {
$stmt = $this->_db->prepare($this->_sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchObject();
if (is_object($row)) {
return $row->Email;
}
return NULL;
} catch (PDOException $e) {
throw $e;
}
}
【问题讨论】:
-
始终在
try中做好准备。 sql 语法错误可以/将会潜入。 -
如果你不打算对异常做任何有意义的,那么就不要抓住它。像这样重新抛出异常只会使堆栈跟踪更难以阅读。
标签: php pdo try-catch prepared-statement