简体   繁体   English

试图获取非对象php变量的属性

[英]Trying to get property of non-object php variable

I am using codeigniter and I have made a function to return name of the user. 我正在使用codeigniter,并且已经制作了一个返回用户名的函数。 Here is the code: 这是代码:

$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->result_array();

$string = $data->u_name.' '.$data->u_surname;

return $string;

When I am using this function i get this error: 当我使用此功能时,出现此错误:

Message: Trying to get property of non-object and recall the line with $string = [...] 消息:试图获取非对象的属性并使用$ string = [...]调用该行

Use foreach loop: 使用foreach循环:

foreach ($data as $row)
{
    echo $string = $data['u_name'].' '.$data['u_surname'];
}

You can try like this.In codeigniter,The row() returns the matched first row according to your condition in object form. 您可以尝试这样。在codeigniter中, row()根据您的条件以对象形式返回匹配的第一行。

$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->row();//change here

$string = $data->u_name.' '.$data->u_surname;

//echo $string;
return $string;

for more see Codeigniter Result Sets 有关更多信息,请参见Codeigniter结果集

Try this code to return 尝试此代码返回

$this->db->select('*');
$this->db->from('users');
$this->db->where(array('u_id'=>$id));
$query=$this->db->get();
if($query->num_rows()()>0)
{
$data = $query->result();
return $data->u_name.' '.$data->u_surname;

}

This is because the function you chose to generate results for you query. 这是因为您选择为查询生成结果的函数。

$data = $query->result_array();

result_array() returns the results in an array even if you only had one result, so when you try to $data->u_name for instance, you have this error because the array does not have that property. 即使只有一个结果,result_array()也会在数组中返回结果,因此,例如,当您尝试$ data-> u_name时,会出现此错误,因为数组没有该属性。

You can do a foreach on $data and perform your logic or use other methods to get the result from the query like $query->row_array(); 您可以在$ data上执行foreach并执行逻辑,或使用其他方法从查询中获取结果,例如$ query-> row_array();。

Take a look on the codeigniter documentation: Generating Query Results 看一下codeigniter文档: 生成查询结果

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

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