Issue
How can I to achieve checking roles using the following snippets? What I want to attain is to be able to authenticate user depending on assigned roles. in_array()
not work for returned array.
Returned array is:
array (size=2) 0 => object(stdClass)[40] public 'role' => string '2' (length=1) 1 => object(stdClass)[41] public 'role' => string '5' (length=1)
Data:
DB TABLE
id user_id role
1 4 2
2 4 5
Model
//get logged user roles
public function user_roles($id){
$userDB = $this->quickDB();
$userdata = $userDB->query("SELECT role
FROM role_assignment
WHERE user_id = $id
")->result();
$userDB->close();
return ($userdata);
}
Controller:
public function user_roles()
{
$roles=$this->Master_model->user_roles('4');
if (in_array("1", $roles))
{
echo "Admin<br>";
}
if (in_array("2", $roles))
{
echo "Teacher<br>";
}
if (in_array("5", $roles))
{
echo "Academic<br>";
}
}
Solution
in_array
in your code can't work. You need to make two changes.
First - change your DB output to array, now you are getting objetct:
$userdata = $userDB->query("SELECT role
FROM role_assignment
WHERE user_id = $id
")->result_array();
Second - itterate through DB result and return modified array:
$user_roles = array();
foreach ($userdata as $val) {
$user_roles[] = $val['role'];
}
return $user_roles;
Both changes are inside user_roles function in your model.
Answered By - shaggy
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.