首页 > 解决方案 > 带有查询字符串的 CI3 高级搜索过滤器

问题描述

我正在尝试在我的 Codeigniter 3 站点中实现高级搜索。

当前的搜索功能运行良好(搜索所有记录)。

我有一个带有一个输入 ( searchTerm) 的简单 HTML 表单,它发送一个查询字符串q=。我的基本搜索语法是;

$searchTerm  = $this->input->get('q'); 
if ($searchTerm) { 
    $this->db->from('records');
    $this->db->where('column1', $searchTerm); 
    $this->db->where('column2', $searchTerm);
    $this->db->where('column3', $searchTerm);
    // $this->db->where('etc', $searchTerm);
    $query = $this->db->get();
    return $query->result_array();
}

我的数据库中大约有 20 列。

我想在我的 HTML 表单中添加额外的三个输入,用于搜索这些数据库列;

我是否需要为每个可能的搜索组合创建一个新函数?用户可以搜索其中一个。一个另一个。只有一个

那会是很多if/else语句吗?例如;

 - if searchTerm is not empty
 - if searchTerm is not empty and startYear is not empty
 - if startYear is empty and endYear is not empty
 - etc
 - etc

也许有更有效的方法来做到这一点?

我不想使用任何额外的库或插件。

任何建议表示赞赏。

标签: phpcodeigniterif-statementsearchcodeigniter-3

解决方案


您可以确保您发布的字段与您的数据库字段具有相同的名称,并执行以下操作:

$search_query = $this->input->get(); //assuming your query strings are only search terms 

foreach($search_query as $search){
    $this-db->or_where($search, $search);  //or where, you could also you $this-db->where();  which will produce where and foreach element 
}
return $this-db->get('records')->result(); 

如果您的查询字符串包含搜索词以外的内容,您可以$search_query在继续循环之前取消设置它们。


推荐阅读