php - 带有查询字符串的 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 表单中添加额外的三个输入,用于搜索这些数据库列;
- 集合 ID
- 开始年
- 年底
我是否需要为每个可能的搜索组合创建一个新函数?用户可以搜索其中一个。一个和另一个。只有一个。
那会是很多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
也许有更有效的方法来做到这一点?
我不想使用任何额外的库或插件。
任何建议表示赞赏。
解决方案
您可以确保您发布的字段与您的数据库字段具有相同的名称,并执行以下操作:
$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
在继续循环之前取消设置它们。
推荐阅读
- iptables - 如何通过 iptables 阻止 FIN-WAIT-2?
- javascript - 在聊天应用程序中获取最新消息 - Django
- nginx - Nginx 反向代理到两个服务
- java - 尝试使用 apache POI 从 excel 表中检索数据
- php - (PHP) 试图控制包含函数
- r - R ggplot2 geom_bar barplot:在不修改数据框的情况下按计数对条形图进行排序,并且因子标签具有含义
- python-datetime - 通过排除 pandas 数据框中的非营业时间来计算两个日期之间的营业时间
- azure - 通过 API 检索 Azure AppInsights 实时指标
- vue.js - Vue没有看到从单独组件传递的函数
- javascript - 如何在 Web Worker 中使用 Azure App Insights?