Converting mysql to mysqli - how to get superglobal connection object?

Tags: php mysql mysqli
By : Richard

I am trying to convert code from mysql to mysqli. The code uses a single mysql_connect in a file which is included by every other file.

mysql_connect returns a MySQL link identifier that is a superglobal so you can rely on having a database connection available in any of your own functions.

It looks like with mysqli_connect this is not the case, the object returned isn't global.

Does this mean I have to add : global $mysqli; at the top of every function, or is there an way of making it a superglobal?

By : Richard


A very simple way to do this would be with a fixed database class, just to hold the mysqli connection object:

class Database {
    public static $connection;

Database::$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

Then you can access it in the normal ways:

$sql = 'SELECT * FROM table';
$result = Database::$connection->query($sql);
$result = mysqli_query(Database::$connection, $sql);
echo 'Server info ' . mysqli_get_server_info(Database::$connection);

Relying on the fact that PHP will use the last opened connection resource if you don't specify one, is probably not a very good idea.
What happens if your application changes and you need two connections, or the connection is not there?
So it seems you need to do some refactoring anyway.

Here's a solution similar to Karsten's that always returns the same mysqli object.

class DB {
    private static $mysqli;
    private function __construct(){} //no instantiation

    static function cxn() {
        if( !self::$mysqli ) {
            self::$mysqli = new mysqli(...);
        return self::$mysqli;

By : meouw

To introduce some oop to you and solve your problem, you could use a class like this:

class MyDatabase
    private static $_connection;

    public static function connect()
        $mysqli = new mysqli(...);
        self::$_connection = $mysqli;

    public static function getConnection()
        return self::$_connection;

In your database-connection file you would load this class and execute MyDatabase::connect(); once. To get the $mysqli-connection anywhere in your script, just call MyDatabase::getConnection();.

By : Karsten

This video can help you solving your question :)
By: admin