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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.