• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get data objects in controller

I'm really new to this so excuse my query on something that is probably fundamental but...

I have a controller that has the model in the constructor, I have created a method in the model which grabs a record from the database.
I call it in my controller like so:

$data['user'] = $this->jobseekers_model->getUser($userId);

Now I have checked and it is returning an array, I can see it using print_r but I can't seem to figure out how to get an array element, I am trying to set a session var using:

$newdata = array(
        'username'  => $user['username'],
        'email'     => $user['email'],
        'logged_in' => TRUE

 but then I get the error:
Message: Undefined variable: user

can anyone please advise?
Do I need to loop through the array first an assign each array element to a new array? Surely not?

You need to pass it to your view.

PHP Code:

And inside that view:
PHP Code:
<?php echo $user['username'];?>

Ok thanks I get that, but then how would I get the variables to create the session vars in the controller, because I assume that's where I would need to set them, in the controller not the view?

You access multi array like this.
PHP Code:
$newdata = array(
'username'  => $data['user']['username'],
'email'     => $data['user']['email'],
'logged_in' => TRUE

I still can't get it working, I'll try and break the code down into it's simplest parts:

In my model:
// will include the password later
public function jobseekersLogin($email, $password) {

  $this->db->where('lc_email', $email);
  $query = $this->db->get();

  if ($query->num_rows() == 1) {
    return $query->result_array();
    } else {
      return false;

in my controller:

// This is returning a large array as tested with print_r
$data['user'] = $this->jobseekers_model->jobseekersLogin($jbsEmail, $jbsPassword);

107: $userId = $data['userData']['lc_id'];

A PHP Error was encountered
Severity: Notice
Message: Undefined index: lc_id
Filename: controllers/Jobseekers.php
Line Number: 107

lc_id is the primary id column in the database, I would have thought with this code all columns would now be available i.e
$userId = $data['userData']['email];
$userId = $data['userData']['first_name'];

etc etc?

I have got it working, not entirely sure why but it was the query in the model, I changed it from:

return $query->result_array();


return $query->row_array();

and now it all works, thanks for your help it has helped me nail some other bits that weren't working too.

result_array generates a multi array, for when you want users

PHP Code:
$data['user'][0]['username']; // 0 = first user, 1 = second ... 

row_array generates a single array, for when you want a single user

PHP Code:

Got it, nice one, thanks very much.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

Users browsing this thread:
1 Guest(s)

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2018 MyBB Group.