I try to connect to the database (MySQLi) only once, but I am having problems with this.
How to create a global connection for the whole script? There are several files (index.php, / classes / config.class.php, / classes / admin.class.php, etc.).
I tried the following:
In: 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']); }
Again, in 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; }
I am using a class with the following code: $config = new db();
I am really puzzled by how I should do this. Can anyone help?
--- Edit --- This is my new config.class.php file:
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; }
And here is how I download it:
require_once("classes/config.class.php"); $config = new db(); $sql = db::getConnection();
However, when starting real_escape_string, the following errors occur:
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