我在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();
}
答案 0 :(得分:0)
你仍然可以在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作为另一个问题的解决方案。它有点先进,但一旦你了解它,它就会更高效。