简体   繁体   中英

Why does CodeIgniter return my SQL query as an array, with an object inside?

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' ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM