0
我是veeery在PHP
新,我试图做这个简单的任务:从MySql
数据库中获取数据。每次我需要的东西时创建新的mysql连接对象
我做了一个单例类数据库comunicate:
class Database {
private static $db = null;
private $servername;
private $username;
private $password;
private $connection;
private function Database(){
$this->servername = "localhost";
$this->username = "user";
$this->password = "123456";
}
public static function get_database(){
if(!static::$db){
static::$db = new Database();
}
return static::$db;
}
function start_connection(){
$this->connection = new mysqli($this->servername,
$this->username,
$this->password);
}
function execute_query($query){
$this->start_connection();
[...]
$this->disconnect();
}
function disconnect(){
$this->connection->close();
}
[...]
}
该代码可以正常使用,但有一件事困扰着我。我想知道是否真的需要创建一个新的连接对象,new mysqli()
,每次我拨打start_connection()
。有什么像reconnect
?
这完全取决于你。大多数人只是在构造函数中连接到数据库一次,然后重新使用该连接的一切。但一般来说,如果您需要使用不同凭据访问数据库,那么您只需要多次连接到数据库。 –
你有没有听说过“单身”模式?也许你可以在你的数据库类中使用类似的东西。 – Mindastic
为什么不将mysqli对象存储在静态$ db变量中并在get_database()函数中初始化一次?这样你总是可以使用这个单一的连接。 – FLXN