1

I have constructed a model within codeigniter named 'Profile_model' which contains the following sql queries, and is supposed to return the user_name of the user with a given id ('userpdata' is the table which contains this info) :

public function get_username($id)
{
  $query = $this->db->select('user_name')
                    ->where('id', $id)
                    ->get('userpdata');
  return $query->result();
}

I have passed in the $id of the current user from the controller like so (model is referred to as 'profile'):

$userId = strval($this->ion_auth->get_user_id());
$data = array(
    'username' => $this->profile->get_username($userId)
    );

$this->load->view('user/profile', $data);

user/profile view:

<?php 
  print_r($username);
?>

This returns the string:

Array ( [0] => stdClass Object ( [user_name] => hish ) )

Which appears to be an array containing an object. How can I retrieve just the user_name 'hish'?

1
  • generally search results are always an array of arrays or an array of objects. CI's undoubtedly using its db library of choice's "fetchObject()" function when retrieving results. Commented Dec 11, 2015 at 18:58

1 Answer 1

1

Change $query->result(); to $query->row(); so that you don't get an array. The result() method returns an array of rows, each of which is an object. The row() method returns the first object of the result set.

public function get_username($id)
{
  $query = $this->db->select('user_name')
                    ->where('id', $id)
                    ->get('userpdata');
  return $query->row();
}

You will end up with the object that contains the property user_name. You could either get the value of it in the controller.

$user = $this->profile->get_username($userId);
$data = array(
    'username' => $user->user_name
);

Or you could get it in the view without changing the controller and use this $username->user_name.

Codeigniter - Generating Query Results

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I've got it to work. Thanks! I'll accept your answer in a few minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.