2

I have the problem, that the following if condition always goes into the first if condition, never into the elseif condition.

This is my code below :

if ($this->session->has_userdata('role') == 1) {
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('adashboard');    
} elseif ($this->session->has_userdata('role') == 2) {
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('udashboard');
}

Can you tell my why?

Pradeep
  • 9,667
  • 13
  • 27
  • 34
  • 2
    Related, if not duplicate: [Is $this->session->userdata and $this->session->has_userdata same when use for authenticate in CodeIgniter?](https://stackoverflow.com/questions/44411551/is-this-session-userdata-and-this-session-has-userdata-same-when-use-for-a) – GolezTrol Aug 07 '18 at 13:31
  • You have same code for if and else – Nadun Kulatunge Aug 07 '18 at 13:31
  • @NadunKulatunge He redirects to two different pages. – Philipp Maurer Aug 07 '18 at 13:32
  • 2
    Like mentioned in the accepted answer of the question that @GolezTrol linked in his comment, the function `has_userdata()` just returns a `bool` that indicates whether or not the key exist, not the value behind it. – Philipp Maurer Aug 07 '18 at 13:36

2 Answers2

0

Hope this will help you :

Use userdata instead of has_userdata : userdata returns Value of the specified item key

if ($this->session->userdata('role') == 1) 
{
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('adashboard');    
} 
elseif ($this->session->userdata('role') == 2) 
{
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('udashboard');
}

For more : https://www.codeigniter.com/user_guide/libraries/sessions.html

Pradeep
  • 9,667
  • 13
  • 27
  • 34
0

Hope this will help you

has_userdata() check whether given session index is set or not and it return boolen value.

$this->session->has_userdata('role') ; 

this code check whether role is set or not. So in your case it returns true that's equivalent to 1.

In your case you need to use userdata() instead of has_userdata().

$role=$this->session->userdata('role');
if ($role == 1) {
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('adashboard');    
} elseif ($role == 2) {
    $this->session->set_flashdata('success', 'Welcome ' . $userInfo[0]->name . '!');
    redirect('udashboard');
}
Feroz
  • 143
  • 8