I used to create a Database class as a Singleton like this. Not everyone likes this method, but its convenient for wrapping things up.
class Database
{
private $_instance = null;
public static function getInstance()
{
if( !(self::$_instance instanceof MySQLi) )
self::createInstance();
return self::_instance;
}
private static function createInstance()
{
// Create DB object here and store in self::$_instance
}
}
There would obviously be passing of configuration data and what not, that's just a psudo-summary. You could use that class like:
$myDb = Database::getInstance();
This will recreate your database connection on each individual request, but will reuse the same connection if you make multiple queries in a single request.
As far as storing your MySQLi object in the SESSION, it just won't work. You are allowed to serialize objects and place them in the $_SESSION
, but some objects are special and intentionally disallow it. For example, if you try to serialize a PDO object to store in the SESSION, it will throw this error:
Fatal error: Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances' in ...