【发布时间】:2017-03-13 18:27:56
【问题描述】:
我有以下类来处理我的大部分数据库查询、准备好的语句等。以下只是我所学课程的一个示例。
PhP (database.php)
class Database{
public $mysqli;
function __construct(){
// Open the connection to the DB on construct
$this->open_connection();
}
private function open_connection(){
$this->mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die("Database connection failed: " . mysqli_connect_error() . " ( " . mysqli_connect_errno() . " ) ");
}
}
/*
* Creates a user
*/
public function create_user($username, $password){
$stmt = $this->mysqli->prepare("INSERT INTO Users(username,password,dateCreated) VALUES(?,?,NOW())");
$password = $this->hash_password($password);
$stmt->bind_param("ss", $username, $password);
if( !$stmt->execute() ) :
$error = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
endif;
$stmt->close();
return $error;
}
// ....
}
$db = new Database();
因为我每次在页面加载时都在需要该文件时实例化该类,所以我应该如何关闭与数据库的连接?我可以让它保持打开状态吗?
【问题讨论】: