I am trying to connect to a database (MySQLi) just once, but am having problems doing so.
How do I make a connection global for the entire script? There are multiple
Personally, I use a singleton class. Something like this:
<?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;
}
}
?>
Then just use $db = Database::getConnection();
wherever I need it.