Question

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?

Was it helpful?

Solution

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;
    }
}        

//use
DB::cxn()->prepare(....

OTHER TIPS

I usually make a function:

$mysqli = new mysqli(...);

function prepare($query) {
  global $mysqli;
  $stmt = $msqyli->prepare($query);
  if ($mysqli->error()) {
    // do something
  }
  return $stmt;
}

function doStuff() {
  $stmt = prepare("SELECT id, name, description FROM blah");
  // and so on
}

and then call that. That being said, I've since abandoned mysqli as being too bug-ridden to be considered usable. Shame really.

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();.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top