I have a PHP database connection that works perfectly when accessed like:
$con = mysqli_connect("localhost","username","password","database");
$result = mysqli_query($con, $query);
I can also access it in functions by passing it as an argument:
function test($con, $args) {
$query10 = "select name from table where id = '$args[0]'";
$result10 = mysqli_query($con, $query10);
}
test($con, array('value1','value2'));
However, when I try to access the connection from a function that is called by another function:
mainFunction() {
test($con, array('value1','value2'));
}
I get "faultCode0faultStringWarning:mysqli_query() expects parameter 1 to be mysqli, null given".
Passing the variable to the mainFunction and then on to the second function works, but it creates very unreadable code with way too many parameters, because the same applies for every other variable, too.
So I tried using global variables, but for some reason they don't work. Running
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
returns 2, which leads me to suspect that something with the PHP configuration is wrong, because according to the PHP docs (http://php.net/manual/en/language.variables.scope.php) it should return 3.
How can I get global variables to work OR is there another way to access variables from nested functions without passing them on multiple times?
The PHP version is 5.3.10-1ubuntu3.8 and the Zend framework is installed, too. If you need any other information please let me know.
3in any version of PHP. If it doesn't for you, that means there's more to the code than you're showing. You could makeglobalwork if you fixed whatever is wrong with the code you're not showing us.