Viruzzz
Viruzzz

Reputation: 1

Codeigniter user_model Invalid argument supplied for foreach()

I have a problem with user_model.php, below it's the errors:

A PHP Error was encountered Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: models/user_model.php

Line Number: 18

Backtrace:

File: \httpdocs\application\models\user_model.php Line: 18 Function: _error_handler

File: \httpdocs\application\controllers\user.php Line: 9 Function: check_role

File: \httpdocs\index.php Line: 292 Function: require_once

user_model.php

public function check_role()
{
    $user_id = $this->session->userdata('admin_user_id');
    // get roles
    if ($user_id) {
        $row = $this->db->get_where(TBL_USERS, array('id' => $user_id))->row();
        $roles = $this->db->get_where(TBL_ROLES, array('id' => $row->role_id))->row_array();
        foreach ($roles as $key => $value) {
            $this->session->set_userdata($key, $value);
        }
    }
}

what is wrong with foreach?

Upvotes: 0

Views: 1166

Answers (1)

AnkiiG
AnkiiG

Reputation: 3488

Try to check count($roles) before foreach().

public function check_role()
{
    $user_id = $this->session->userdata('admin_user_id');
    // get roles
    if ($user_id) {
        $row = $this->db->get_where(TBL_USERS, array('id' => $user_id))->row();
        $roles = $this->db->get_where(TBL_ROLES, array('id' => $row->role_id))->row_array();
        if(count($roles)>0)
        {
            foreach ($roles as $key => $value) {
               $this->session->set_userdata($key, $value);
            }
        }
    }
}

Upvotes: 0

Related Questions