我在PHP数据库连接方面遇到了一些疑问。既然我不能在我的方法上放一个很大的try/catch/finally块(Java风格),那么当大小/逻辑趋于增长时,正确关闭所有连接和准备好的语句的最佳方法是什么?考虑下一种方法,一切都是正确的吗?
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();
}发布于 2012-02-28 09:25:45
您仍然可以在PHP中使用try/catch:
public function createRegister($register) {
$this->openConnection();
$query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
try {
// This line is not needed
// $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()) {
throw new DAOException("Failed to execute statement: " . $statement->error);
}
$statement->close();
} else {
throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
}
} catch (Exception $e) {
if ((isset($statement)) && (is_callable(array($statement, 'close')))) {
$statment->close();
}
$this->closeConnection();
throw $e;
}
$this->closeConnection();
}这对于为一个特定任务建立连接很有效,但是如果您希望为也需要访问相同模式的多个任务共享相同的连接,该怎么办呢?您可能希望考虑一种更高级的解决方案,使用单例/工厂模式创建和访问数据库连接。我发布了这样一个example,作为对另一个问题的解决方案。它有点高级,但一旦你掌握了它,它的性能就会更好。
https://stackoverflow.com/questions/9475038
复制相似问题