Jump to content

Code that works outside of function but not as a function


Fenhopi

Recommended Posts

Hi, I have this piece of code:

function GetAlerts(){
$username = mysql_real_escape_string($_SESSION['username']);
$GetStatus = "SELECT comments.status, friends.status FROM comments, friends WHERE comments.person='$username' AND friends.user2='$username'";
$Connect = $database->query($GetStatus);
$NumberRows = mysql_num_rows($Connect);
return $NumberRows;
}

When I call the function I get:

Fatal error: Call to a member function query() on a non-object

And it points to the $GetStatus line.

However, if I just use the code like this:

$username = mysql_real_escape_string($_SESSION['username']);
$GetStatus = "SELECT comments.status, friends.status FROM comments, friends WHERE comments.person='$username' AND friends.user2='$username'";
$Connect = $database->query($GetStatus);
$NumberRows = mysql_num_rows($Connect);
        echo $NumberRows;

it works perfectly..

 

Any ideas?

 

Thanks in advance.

Functions have their own variable scope. Meaning any variables that are defined outside of them are not available within them. The same applies with variable you define within the function are available outside of them.

 

To get around this you need to pass the $database variable to your GetAlerts() function.

 

Manual page on Variable Scope and Functions

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.