简体   繁体   English

为什么CodeIgniter以数组的形式返回SQL查询,且其中包含一个对象?

[英]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) : 我在codeigniter中构造了一个名为'Profile_model'模型 ,该模型包含以下sql查询,并应返回具有给定id的用户的user_name“ userpdata”是包含此信息的表):

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' ): 我已经从控制器中传入了当前用户的$ id,如下所示(模型称为'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 ) ) 数组([0] => stdClass对象([user_name] => hish))

Which appears to be an array containing an object. 这似乎是一个包含对象的数组。 How can I retrieve just the user_name 'hish' ? 如何仅检索user_name'hish '

Change $query->result(); 更改$query->result(); to $query->row(); $query->row(); so that you don't get an array. 这样就不会得到数组。 The result() method returns an array of rows, each of which is an object. result()方法返回一个行数组,每个行都是一个对象。 The row() method returns the first object of the result set. row()方法返回结果集的第一个对象。

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 . 您将最终得到包含属性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 . 或者,您可以在视图中获取它而无需更改控制器,并使用此$username->user_name

Codeigniter - Generating Query Results Codeigniter-生成查询结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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