php - Prepared statement inside or outside a try/cach? -


my doubt whether prepared statement should inside or outside try/catch block.

(this example method user class)

should this?

public function getemail( $id_user ) {   $this->_sql = 'select email '.tbl_users.' 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;   }   } 

or this?

public function getemail( $id_user ) {   $this->_sql = 'select email '.tbl_users.' 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;   } } 

the prepare() method can potentially throw pdoexception should include call prepare inside of try block. in both of examples you're re-throwing exception. unless you're going handle exception inside of catch block effect same.


Comments