douwo8358 2017-10-14 21:06
浏览 16
已采纳

Codeigniter搜索功能会抛出错误

I have written some code to make a search in the CODEIGNITER3 framework. When I insert 2 or more words to search input, it works great, however, when I enter just 1 word, it gives this error.

enter image description here

How can I solve this problem? Here is my controller:

function search() {
            $keyword = strip_tags($this->input->get('searchforcourses'));
            $keyword = explode(" ", $keyword);

            $data['title'] = 'Bütün Kurslar Burada';
            $data['courses'] = $this->courses_model->courses_search($keyword);


            $this->load->view('templates/header');
            $this->load->view('courses/courses', $data);
            $this->load->view('templates/footer');
        }

And here is my model:

function courses_search($keyword) {
            $this->db->select('*');
            $this->db->from('courses');
            $this->db->like('title',$keyword[0]);
            $this->db->or_like('title',$keyword[1]);
            $this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
            $this->db->join('categories', 'categories.id = courses.category_id', 'left');
            $query = $this->db->get();
            return $query->result_array();
        }

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongshai2022 2017-10-14 21:25
    关注

    The error means you are trying to access an unexisting key 1, your code is wrong on the model level, your code is only getting two keywords, what if the user searched for three keywords? are you just going to ignore them?

    I suggest doing it like this:

    function courses_search($keyword) {
        $this->db->select('*');
        $this->db->from('courses');
        // You should consider limiting the number of keywords to avoid long loops
        // Limits to 20 keywords
        $keyword = array_slice($keyword, 0, 19);
        // You can also limit it in the 3rd parameter of the explode function
        // Loop through the keywords
        forearch($keyword as $key){
            $this->db->or_like('title',$key);
        }
        $this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
        $this->db->join('categories', 'categories.id = courses.category_id', 'left');
        $query = $this->db->get();
        return $query->result_array();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题