Sql 类codeigniter子句重写where子句

Sql 类codeigniter子句重写where子句,sql,codeigniter,where-clause,Sql,Codeigniter,Where Clause,至少这似乎正在发生。我正在尝试为一个网站创建一个搜索栏,它确实起作用了,只是它没有阅读where条款,而where条款只会收回已批准的内容。你可以看出为什么这会成为一个问题 不管怎么说,这就是我的模型 $match = $this->input->post('search'); $this->db->where('approved', 'y'); $this->db->like('description', $match); $this->

至少这似乎正在发生。我正在尝试为一个网站创建一个搜索栏,它确实起作用了,只是它没有阅读where条款,而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();
当我打印查询时,它似乎看到了where子句,但当我把东西拿回来时,它会把未经批准或审查的东西拉回来

这是我打印的查询

SELECT * FROM (`story_tbl`) WHERE `approved` = 'y' AND `description` LIKE 
'%another%' OR `title` LIKE '%another%' OR `body` LIKE '%another%' OR 
`author` LIKE '%another%'
您的查询应该是

SELECT * FROM (`story_tbl`) WHERE `approved` = 'y' AND (`description` LIKE
'%another%' OR `title` LIKE '%another%' OR `body` LIKE '%another%' OR
`author` LIKE '%another%')
检查那些括号。因此,最好的选择是使用普通的
$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');
编辑:

因此,此查询将返回所有行,其中approved='y'或title、body、author与'other'匹配

在我发布的查询中

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

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

您可以使用codeigniters的group_start()和group_end()来实现这一目标。代码可以这样修改

$match = $this->input->post('search');      
$this->db->where('approved', 'y');

$this->db->group_start(); //start group
$this->db->like('description', $match);
$this->db->or_like('title', $match);
$this->db->or_like('body', $match);
$this->db->or_like('author', $match);
$this->db->group_end(); //close group

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

return $query->result(); 

我为什么要这些括号?这就是codeigniter将其打印到页面的方式,我上面发布的查询仍然忽略了我的第一个where子句。我很困惑为什么在活动记录上使用$this->db->query更好?where子句被忽略,因为没有括号。你需要了解AND和OR是如何工作的。我确实了解它们是如何工作的,但当我将代码粘贴到上面时,会出现500个错误符号不应该有什么区别,即使我在我的sql编辑器中输入上面的查询,它仍然会忽略第一个where子句。这是不应该发生的。我在SQL中检查了代码,它没有忽略第一个where子句。
$match = $this->input->post('search');      
$this->db->where('approved', 'y');

$this->db->group_start(); //start group
$this->db->like('description', $match);
$this->db->or_like('title', $match);
$this->db->or_like('body', $match);
$this->db->or_like('author', $match);
$this->db->group_end(); //close group

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

return $query->result();