如果“未找到结果”或没有输入“输入”,则编码错误;其他工作正常

时间:2016-01-05 16:18:16

标签: php codeigniter codeigniter-3

我正处于学习阶段并尝试开发此搜索结果应用。 如果找到结果,一切正常,但如果没有输入或没有结果,则显示这两个错误;

  

消息:未定义的偏移量:0

     

消息:尝试获取非对象的属性

这是发生错误的地方search_model.php

function get_city_id_by_input($keyword){
    $this->db->select('id');
    $this->db->from('vbc_city');
    $this->db->where('v_city_name', $keyword);
    $query = $this->db->get();
    $query_result = $query->result();
    $row = $query_result[0];
    return $row->id;
}

和控制器:

$keyword = $this->input->post('search[1]');
$city_id = $this->search_model->get_city_id_by_input($keyword);
$data['results'] = $this->search_model->get_search_results($city_id);
$this->load->view('search', $data);

1 个答案:

答案 0 :(得分:1)

试试这个

在模型中

function get_city_id_by_input($keyword){
    $this->db->select('id');
    $this->db->from('vbc_city');
    $this->db->where('v_city_name', $keyword);
    $query = $this->db->get();
    $query_result = $query->result_array(); # Changed
    if (empty($query_result)) {
        return FALSE;
    }
    elseif (count($query_result) > 1) {
        return 0;
    }
    else{
        $rowId = $query_result[0]['id']; # Changed
        return $rowId; # Changed    
    }
}

在控制器中

$keyword = $this->input->post('search[1]');
if (empty($keyword)) {
    echo "Input is Empty";
}
else{
    $city_id = $this->search_model->get_city_id_by_input($keyword);
    $result = $this->search_model->get_search_results($city_id);
    if ($result == FALSE) {
        echo "No Data Found";
    }
    elseif ($result == 0) {
        echo "Multiple of records founds";
    }
    else{
        $data['results'] = $result
        $this->load->view('search', $data);
    }

}