PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 29, 2022

[FIXED] Checking in_array from db with codeigniter

 January 29, 2022     codeigniter, codeigniter-3, mysql, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing