我只想连接一个数据库(MySQLi),但是我遇到了这样的问题。
如何为整个脚本建立全局连接?有多个文件(index.php,/ classes / config.class.php,/ classes / admin.class.php等)。
我尝试了以下内容:
在:config.class.php
public static $config = array();
public static $sql;
function __construct() {
// database
db::$config['host'] = 'localhost';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
db::$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
再次,在config.class.php
中public function contectToDatabase($sql){
$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
$this->sql = $sql;
}
我使用以下代码的类:
$config = new db();
我真的很困惑我要怎么做。有人可以帮忙吗?
---编辑--- 这是我的新config.class.php文件:
public static $config = array();
public static $sql;
private static $db;
private $connection;
public function __construct() {
// database
db::$config['host'] = '_';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
$this->connection = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if($db == null){
$db = new db();
}
return $db->connection;
}
这就是我加载它的方式:
require_once("classes/config.class.php");
$config = new db();
$sql = db::getConnection();
但是,运行real_escape_string会导致以下错误:
Warning: mysqli::real_escape_string() [mysqli.real-escape-string]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 20
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 28
答案 0 :(得分:14)
就个人而言,我使用的是单例类。像这样:
<?php
class Database {
private static $db;
private $connection;
private function __construct() {
$this->connection = new MySQLi(/* credentials */);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if (self::$db == null) {
self::$db = new Database();
}
return self::$db->connection;
}
}
?>
然后在我需要的地方使用$db = Database::getConnection();
。