lpxxfaintxx Posted November 30, 2008 Share Posted November 30, 2008 Okay, so I got cocky and decided to give functions a go. (yes, I'm a newbie). I have profilepic.php and classes.php In profilepic.php, I called in the classes, include("classes.php"); and *attempted* to create a simple function: function queryuser($sessid){ $query = mysql_query("SELECT * FROM users WHERE user_id = '$sessid'") or die(mysql_error()); $row = mysql_fetch_array($query); } Pretty simple so far. I'm trying to get the function to work properly by doing: $sessid = $_SESSION['id']; queryuser($sessid); (I'm sure $sessid is storing its value properly, I have checked by echoing it.) BUT, when I try using any $row[field], the value is empty. In (my) theory, it should store the proper data in the variables, but I guess I'm missing something. Any idea? Thanks! Link to comment https://forums.phpfreaks.com/topic/134843-my-simple-function-not-working-as-expected/ Share on other sites More sharing options...
flyhoney Posted November 30, 2008 Share Posted November 30, 2008 <?php function queryuser($sessid){ $query = mysql_query("SELECT * FROM users WHERE user_id = '$sessid'") or die(mysql_error()); $row = mysql_fetch_array($query); return $row; } $user = queryuser($sessid); ?> Link to comment https://forums.phpfreaks.com/topic/134843-my-simple-function-not-working-as-expected/#findComment-702146 Share on other sites More sharing options...
lpxxfaintxx Posted November 30, 2008 Author Share Posted November 30, 2008 Thanks! Worked perfectly. Link to comment https://forums.phpfreaks.com/topic/134843-my-simple-function-not-working-as-expected/#findComment-702149 Share on other sites More sharing options...
unkwntech Posted November 30, 2008 Share Posted November 30, 2008 The problem you are having is because of the scope, all variables defined inside a function are limited to use inside that function, the only way to get data out of a function (as a variable) is to use return. In the example flyhoney gave 'return $row;' is making $row available outside the function as a global variable. This same thing basicly applies to variables outside the function to get access to them you must either a) use global, like this: $myVar = 'hello'; function myFunc() { global $myVar; //Now I can use $myVar //However none of my changes will be reflected outside the function unless I 'return' it. } the other option is to pass the variable as a parameter to the funtion like so: $myVar = 'hello'; function myFunc($myVar) { global $myVar; //Now I can use $myVar //However none of my changes will be reflected outside the function unless I 'return' it. } myFunc($myVar); //now you must use the variable when you call the function Link to comment https://forums.phpfreaks.com/topic/134843-my-simple-function-not-working-as-expected/#findComment-702159 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.