Convert mysql to mysqli - how to get a super global connection object?

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

mysql_connect returns the MySQL link identifier, which is superglobal, so you can rely on the availability of a database connection in any of your own functions.

It seems that with mysqli_connect this is not the case, the returned object is not global.

Does this mean that I need to add: global $ mysqli; at the top of each function, or is there a way to make it superglobal?

+3
source share
4 answers

Relying on the fact that PHP will use the last open connection resource, unless you specify it, is probably not a good idea.
What happens if your application changes and you need two connections, or the connection does not exist?
It looks like you still need to do refactoring.

Here, a solution like Carsten 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(.... 
+4
source

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 it. Having said that, I have since left mysqli because I am too confused to be considered usable. Shame indeed.

+2
source

To introduce you some problems and solve your problem, you can 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 load this class and run MyDatabase::connect(); once. To get a $ mysqli connection anywhere in your script, just call MyDatabase::getConnection(); .

0
source

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

 class Database { public static $connection; } Database::$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE); 

Then you can access it in the usual way:

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

All Articles