Skip to content
Advertisement

Method returns right value outside of function, inside function returns NULL

Can someone help me understand this? It seams like I have done this a 100 times already, but for some reason I can’t get it to work now.

I have a MySQL class where I do my SQL stuff.

I have a file called ajax.php which I do some AJAX requests to. In this file I have:

$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
$show =$mysql->count('temp_vipalm', "21");   
var_dump($show);

This returns the correct value as I expected. Now I want to use this in a function, so I can make it a little more dynamic, so in the same ajax.php file I create this function:

function menu($barid,$type)
{
    //echo $barid; // returns correct value
    //echo $bartype; //returns correct value

$mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
   //usually $barid and $type goes in here, but I hardcoded the values for testing.
$show =$mysql->count('temp_vipalm', "21");   
var_dump($show);
}

Now when running menu('21', 'temp_vipalm'); it returns NULL.

No matter what I do, it keeps returning NULL when inside the function – can anyone help me understand what’s going on?

Advertisement

Answer

Your $server, $dbuser, $dbpass, and $dbselect variables are global. Within the function scope, you’ll have to declare that those variables are coming from the global scope. Try this:

function menu($barid, $type) {
{
    global $server, $dbuser, $dbpass, $dbselect;
    $mysql = new Mysql($server, $dbuser, $dbpass, $dbselect);
    // ...
}

Note: It would be a better idea to make these constants instead of variables. It’s usually best to avoid variables in the global scope. If you accidentally overwrite one of those values somewhere else in your code, this function will use the wrong values.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement