Fenhopi Posted June 25, 2011 Share Posted June 25, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/240388-code-that-works-outside-of-function-but-not-as-a-function/ Share on other sites More sharing options...
wildteen88 Posted June 25, 2011 Share Posted June 25, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/240388-code-that-works-outside-of-function-but-not-as-a-function/#findComment-1234747 Share on other sites More sharing options...
Fenhopi Posted June 25, 2011 Author Share Posted June 25, 2011 Thank you! Quote Link to comment https://forums.phpfreaks.com/topic/240388-code-that-works-outside-of-function-but-not-as-a-function/#findComment-1234759 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.