Home » Php » mysql – PHP changing to mysqli. Is the mysqli_connection not global?

mysql – PHP changing to mysqli. Is the mysqli_connection not global?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have just started a new PHP project and I was thinking it’s time to follow php suggestion and stop using mysql and swith to mysqli instead. But this gave me a problem.

Normaly my setup is like this

Index.php file and inside this file I have a 2 require statements. One that calls for the db.php file and one other to call a functions.php file. So far so good.

In the functions.php file a have a lot of different functions that is used all over the homepage and many of these are using SQL.
With php old mysql API this was no problem but it seams that the new mysqli api don’t allow connections to be used from included files???

For example in my db.php I have the connect statement. $db = mysql_connect(*******);
And in my function.php I have mysql_query(******) and it works perfect.

But if I change the db.php to $db = mysqli_connect(*****);
Then in my function.php file I can’t call the mysqli_query(***). (I have also tested object oriented but it gives me the same problem).

So how to get around this problem?
Is php expecting me to put the mysqli_connect statement in the beginning of every file that uses sql statements?

How to&Answers:

Yes, MySQLi is object oriented and you need to pass around the $db object to the functions that need a database connection. The procedural alternatives also require the $db object to work. This is for your own good, as implicit global connections (actually: global state in any form) are bad practice. That the mysql extension allowed implicit connections was not good to begin with.

Answer:

Here’s an option – create a static class purely to hold the mysqli object as a public static variable:

class DBi {
    public static $conn;
}
DBi::$conn = new mysqli(HOST, USER, PASS, DB);

… in an include file, database helper or whatever.

Then wherever you want to make a mysqli call you do

DBi::$conn->query(...) 

Makes it as global as you could want. And you can easily start popping your own custom functions (methods) in there if you feel the need – DBi::custom_method()

This is kind of a refinement to the answer given at Converting mysql to mysqli – how to get superglobal connection object?

Answer:

You need to set your $mysqli variable to be global if you need it in functions.

Something like this:

...
function name (){  
        global $mysqli; 

...