我只尝试连接到数据库 (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
最佳答案
就我个人而言,我使用单例类。像这样:
<?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();
。
关于php - 全局变量 - 数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7792974/