Tôi đang cố gắng kết nối với cơ sở dữ liệu (MySQLi) chỉ một lần, nhưng đang gặp sự cố khi làm như vậy.Biến toàn cục - kết nối cơ sở dữ liệu?
Làm cách nào để tạo kết nối toàn cầu cho toàn bộ tập lệnh? Có nhiều tệp (index.php, /classes/config.class.php, /classes/admin.class.php, v.v.).
Tôi đã thử những điều sau đây:
Trong: 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']);
}
Một lần nữa, trong 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;
}
tôi sử dụng lớp với mã sau: $config = new db();
Tôi thực sự bối rối Tôi sẽ làm thế nào. Có ai giúp được không?
--- Chỉnh sửa --- Đây là mới tập config.class.php tôi:
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;
}
Và đây là cách tôi đang tải nó:
require_once("classes/config.class.php");
$config = new db();
$sql = db::getConnection();
Tuy nhiên, chạy một kết quả real_escape_string trong các lỗi sau:
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
Bạn có thể sử dụng [singleton pattern] (http://en.wikipedia.org/wiki/Singleton_pattern) – knittl
hoặc bạn có thể tìm hiểu Dependency Injection thay vì sử dụng [singleton antipattern] (http://stackoverflow.com/ question/4595964/who-needs-singletons/4596323 # 4596323) – Gordon
Yeah… singletons luôn dẫn đến các cuộc tranh luận nóng bỏng. Tôi chỉ cho đầu vào và ý tưởng – knittl