codeigniter like子句覆盖where子句

zaz*_*iki 5 sql codeigniter where-clause

至少这似乎正在发生.我正在尝试为网站创建一个搜索栏,它确实有效,除非它没有读取只会撤回已批准内容的where子句.你可以看出为什么会出现这个问题.

无论如何,这就是我在我的模型中所拥有的

$match = $this->input->post('search');      
$this->db->where('approved', 'y');  
$this->db->like('description', $match);
$this->db->or_like('title', $match);
$this->db->or_like('body', $match);
$this->db->or_like('author', $match);

$query = $this->db->get('story_tbl');

return $query->result();
Run Code Online (Sandbox Code Playgroud)

当我打印出查询时,似乎它看到了where子句,但是当我把这些东西拿回来时,它会拉出未经批准或未经审查的内容.

这是我打印的查询

SELECT * FROM (`story_tbl`) WHERE `approved` = 'y' AND `description` LIKE 
'%another%' OR `title` LIKE '%another%' OR `body` LIKE '%another%' OR 
`author` LIKE '%another%'
Run Code Online (Sandbox Code Playgroud)

sak*_*oon 3

您的查询应该是

SELECT * FROM (`story_tbl`) WHERE `approved` = 'y' AND (`description` LIKE
'%another%' OR `title` LIKE '%another%' OR `body` LIKE '%another%' OR
`author` LIKE '%another%')
Run Code Online (Sandbox Code Playgroud)

检查那些括号。因此,您最好的选择是使用 plain $this->db->query()。如果你坚持使用活动记录,你必须对那些括号这样做 -

$match = $this->input->post('search');
$this->db->where('approved', 'y');
$this->db->where("(`description` LIKE '%$match%'");
$this->db->or_where("`title` LIKE '%$match%'");
$this->db->or_where("`body` LIKE '%$match%'");
$this->db->or_where("`author` LIKE '%$match%')");
$query = $this->db->get('story_tbl');
Run Code Online (Sandbox Code Playgroud)

编辑:

true AND true OR true OR true    //true
false AND true OR true OR true   //true just like your where clause is ignored
false AND false OR false OR true //Still true
false AND true OR false OR false //false
false AND false OR false OR false //false
Run Code Online (Sandbox Code Playgroud)

因此,此查询将返回roved = 'y' 或标题、正文、作者匹配 'another' 的所有行

在我发布的查询中

true AND (true OR true OR true)    //true
false AND (true OR true OR true)   //false, where clause is checked
true AND (false OR false OR false) //false
true AND (true OR false OR false)  //true
Run Code Online (Sandbox Code Playgroud)

这将返回已批准 = 'y' 并且标题或正文或作者或描述与 'another' 匹配的行。我相信这就是您想要实现的目标。