【发布时间】:2012-02-28 01:21:33
【问题描述】:
我在 PHP 数据库连接方面遇到了一些疑问。由于我不能只在我的方法(Java 风格)上放置一个大的 try/catch/finally 块,当大小/逻辑趋于增加时,正确关闭所有连接和准备好的语句的最佳方法是什么?考虑下一个方法,一切都做对了吗?
public function createRegister($register) {
$this->openConnection();
$query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
$result = $this->mysqli->query($query);
if ($statement = $this->mysqli->prepare($query)) {
$statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);
if (!$statement->execute()) {
$this->closeConnection();
throw new DAOException("Failed to execute statement: " . $statement->error);
}
$statement->close();
} else {
$this->closeConnection();
throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
}
$this->closeConnection();
}
【问题讨论】:
-
您真的要为每个查询打开/关闭连接吗?为什么要混合不同层的代码?您应该将查询执行封装到一个单独的函数中..
-
@yi_H:好点。在我的回复中,我提到了通过单例/工厂模式回收连接的能力。
标签: php database connection mysqli prepared-statement