我的疑问是准备好的语句应该在try/catch块内部还是外部。
(这是一个示例方法从我的用户类)
我应该这样做吗?
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;
}
}
prepare()方法可能会抛出PDOException,因此您应该在try块中包含对prepare的调用。然而,在这两个例子中,你只是重新抛出异常。除非你真的要在catch块内部处理异常,否则效果是一样的。