我收到了这个错误:
Trying to get property of non-object
当我尝试使用CodeIgniter搜索学生ID号时。
这是我的控制器代码:
public function get_stud_info($id = "")
{
$stud_info = $this->m_stud_info->get_by_ID($id);
$data['IDno'] = $stud_info->IDno;
$data['LName'] = $stud_info->LName;
$data['FName'] = $stud_info->FName;
$data['Course'] = $stud_info->Course;
$data['Year'] = $stud_info->Year;
$data['Club_num'] = $stud_info->Club_num;
$this->load->view('view_stud_info', $data);
}
这是我的型号代码:
public function get_by_ID($ID)
{
$query = $this->db->where('IDno', $ID)->limit(1)->get('stud_info');
if($query->num_rows() > 0)
{
return $query->row();
}
else
{
return array();
}
}
这是我的观看代码:
<?php
echo "IDNo: $IDno <br/>" ;
echo "LName: $LName <br/>" ;
echo "FName: $FName <br/>" ;
echo "Course: $Course <br/>" ;
echo "Year: $Year <br/>" ;
echo "Club_num: $Club_num <br/>" ;
?>
答案 0 :(得分:1)
当模型为您返回空数组时会出现错误,因此请在访问之前检查模型是否返回任何值。
$stud_info = $this->m_stud_info->get_by_ID($id);
if($stud_info) {
$data['IDno'] = $stud_info->IDno;
$data['LName'] = $stud_info->LName;
$data['FName'] = $stud_info->FName;
$data['Course'] = $stud_info->Course;
$data['Year'] = $stud_info->Year;
$data['Club_num'] = $stud_info->Club_num;
} else {
// assign all values to null here
$data['IDno'] = "";
...
}
答案 1 :(得分:0)
这个怎么样,我认为对你来说会更简单,更容易。
$stud_info = $this->m_stud_info->get_by_ID($id);
if($stud_info) {
$data['IDno'] = isset($stud_info->IDno) ? $stud_info->IDno : '';
...
}