Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

mysqli

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?

like image 405
Richard Avatar asked Jan 24 '23 21:01

Richard


2 Answers

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(....
like image 59
meouw Avatar answered Jan 26 '23 10:01

meouw


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.

like image 38
cletus Avatar answered Jan 26 '23 09:01

cletus