tags:

views:

1231

answers:

3

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?

+1  A: 

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.

cletus
+1  A: 

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

Karsten
+1  A: 

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(....
meouw
personally, i would also use this singleton-like construct, but I didn't want to confuse @Richard with all too much new stuff, as he is used to php4 imo
Karsten