Should I pass my $mysqli variable to each function? Should I pass my $mysqli variable to each function? database database

Should I pass my $mysqli variable to each function?


User-defined functions have their own variable scope in PHP. You need to pass $mysqli to the function as a parameter, or start the function with global $mysqli.

This exact problem is given as an example on the Variable scope page:

However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example, this script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

<?php$a = 1; /* global scope */ function test(){     echo $a; /* reference to local scope variable */ } test();?>


cannot manage it to work without passing to the function the $mysqli variable, but this was not necessary when I used mysql_* deprecated functions!

That is not really correct. Even in the old mysql_* function you actually had to pass the link identifier if you needed to specify to which database connection you were relating to, e.g.:

$result = mysql_query($sql, $link);

Also what this example shows, you had to pass along the $result, too. In case you did left out the $link parameter:

$result = mysql_query($sql);

The mysql extension did look internally for the last used connection. If none would have been found, it would have created a new one with the parameters set in php.ini. That just for your information to better understood why and how this worked in the past.


You could also use connection pooling, it's worth to check this out.

$mysqli = new mysqli('p:localhost', 'username', 'password', 'db_name');