I guess I have a little understanding about functions and how they work.. Idea is to get “user’s group” from database, but I don’t want to write the code evey time when I need it so I decided to put it in function.
function get_role()
{
$user_id = $_SESSION['login_ok'];
$res = mysql_query('SELECT role FROM users WHERE id = "'.$user_id.'"') or mysql_error();
$row = mysql_fetch_array($res);
$role = $row['role'];
}
and then when I need it
get_role();
What I need is $role variable which I will use in if() to grant access to smth. But when I do so, it shows that $role is Undefined variable (when I do that checking with if).
Sorry for probably dumb questions but what am I doing wrong?
Add
return $role;to the end of your function.You then can do
$role = get_role();where you call the function.The reason your code is not working is called variable scope. The $role variable you are creating is only available within the function.
By adding the code above, you return the value of
$rolefrom your function and assign it to a local variable where you called the function.You could also declare
$roleasglobalwhich will make it available everywhere, but this is considered a very bad practice.