对于@Roshan 的代码的解释,因为对于在 CI 中学习 SQL 的人来说,答案可能并不明显。 (我还修复了代码中的错误。)
$q = $this->db
// ->select('*') // you don't need select('*') if you want everything
// ->from('table') // Don't need this either
->where('active', 1)
->where("(col LIKE '%".$search_string1."%' OR col LIKE '%".$search_string2."%' OR col LIKE '%".$search_string3."%' OR col LIKE '%".$search_string4."%')", NULL, FALSE)
->get('table') // add your table name here
->result(); // it's not "->results"
所以您的最终查询将如下所示:
$q = $this->db->where('active', 1)
->where("(col LIKE '%".$search_string1."%' OR col LIKE '%".$search_string2."%' OR col LIKE '%".$search_string3."%' OR col LIKE '%".$search_string4."%')", NULL, FALSE)
->get('table')
->result();
这是上面的要求:
"get all results from 'table'
where active = 1 AND `col` = search_string1
OR where active = 1 AND `col` = search_string2
OR where active = 1 AND `col` = search_string3
OR where active = 1 AND `col` = search_string4
Then assign the result object to $q
一种更简单的查看方式,但更复杂的代码编写方式(但可能更容易理解):
$q = $this->db
// where active=1 AND col LIKE %$search_string1%
->where('active', 1)
->like('col', $search_string1, 'both')
// OR where active=1 AND col LIKE %$search_string2%
->or_where('active', 1)
->like('col', $search_string2, 'both')
// OR where active=1 AND col LIKE %$search_string3%
->or_where('active', 1)
->like('col', $search_string3, 'both')
// OR where active=1 AND col LIKE %$search_string4%
->or_where('active', 1)
->like('col', $search_string4, 'both')
->get('table')
->result();
有时您需要这样做。例如,如果active 可能是多个状态。 on、off、pending 并且您需要检查该字段以了解特定状态。在您的情况下不是必需的,因为 active 始终为 1,但如果 active 可能不仅仅是您想要的,您必须在查询生成器中将其拼写出来。