2017-02-02 3 views
0

codeigniter를 사용하고 있으며 사용자의 이름을 반환하는 함수를 만들었습니다. 여기에 코드입니다 :객체가 아닌 PHP 변수의 속성을 얻으려고 시도합니다.

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

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

return $string; 

내가이 오류를 얻을이 기능을 사용하고 있습니다 :

Message: Trying to get property of non-object and recall the line with $string = [...]

+0

Generating Query Results 당신은 배열을 요청 ('[]')하지만 당신은 객체로 액세스하려는를 ('->') 그것은 작동 – Darren

답변

0

사용 Foreach 루프 :

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

, 나는 $ 변경 데이터를 $ row에 저장하십시오. 하지만 왜? –

+0

result_array() 메서드는 쿼리 결과를 순수한 배열로 반환하거나 결과가 생성되지 않을 때 빈 배열을 반환합니다. 일반적으로 foreach 루프에서이 값을 사용합니다. @TomaszChwicewski – mith

+0

참조 : https://www.codeigniter.com/userguide3/database/results.html @TomaszChwicewski – mith

0

당신은 this.In의 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; 

Codeigniter Result Sets

0

이 코드는

$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; 

} 
0

당신이 쿼리에 대해 선택한 함수가 결과를 생성하기 때문입니다 돌아보십시오 참조하십시오.

$data = $query->result_array(); 

result_array는()는 예를 들어 $ 데이터 -> u_name을하려고 할 때 배열은 해당 속성이 없기 때문에 그래서,이 오류를 가지고, 당신은 하나의 결과 만이 있었다하더라도 배열의 결과를 반환합니다.

$ data에서 foreach를 수행하고 논리를 수행하거나 다른 방법을 사용하여 $ query-> row_array()와 같은 쿼리에서 결과를 얻을 수 있습니다.

된답니다 문서에 살펴 보자

관련 문제