Codeigniter - using session data in view

42,805

Solution 1

Controller code:

public function index() {

    ...
    $data['first_name'] = $this->session->userdata('first_name');
    ...
}

View code:

<?= $first_name; ?>

OR, if you want to pass the data like you currently are, you would access the view data userdata as an array, not a function, ie:

<?= $userdata['first_name'];?>

Solution 2

As I mentioned in the comments , when you assign a value to array $data and pass it through Codeigniter view loader , the data will be available in the view part with variable names same to the array indexes.
for example when you do this:

$data['name'] = "bla bla";
$this->load->view('some_view', $data);  

then the $name variable in the view will contain your passed value. In your case you are assigning an array to $data['userdata']. so the $userdata in the view will an array too.

So do like this:

echo $userdata['firstname'];
echo $userdata['lastname'];  

in the view part.

Share:
42,805
Rich Coy
Author by

Rich Coy

Updated on November 16, 2020

Comments

  • Rich Coy
    Rich Coy over 3 years

    I have a users first and last name stored in session data and I want to echo it out in the view so they can see who they are logged in as. I can't seem to get the data to pass. I'm sure this is something easy but I'm pretty new to CI and the whole MVC thing.

    Controller Code:

    public function index() {
        if($this->session->userdata('admin_signed_in')){
        $this->load->model('dashboard_model');
        $data['userdata'] = $this->session->userdata;
        $data['main_content'] = 'dashboard/dashboard';  
        $this->load->view('common/template', $data);
        } else {
        redirect('signin');
        }
    
    }
    

    View Code:

    <?php echo $userdata('first_name') ?>  <?php echo $userdata('last_name') ?>
    

    Print R Results:

    Array ( [session_id] => 69db0f9ccbfde96d92cc09837067438c [ip_address] => ::1 [user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0 [last_activity] => 1352998508 [user_data] => [0] => Array ( [admin_id] => 10 [first_name] => Richard [last_name] => Coy [admin_role] => 1 ) [admin_signed_in] => 1 )