Jump to content

My SIMPLE Function Not Working as Expected?


lpxxfaintxx

Recommended Posts

Okay, so I got cocky and decided to give functions a go.  :D (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!

<?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);
?>

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

 

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.