【问题标题】:MySQLi query issueMySQLi 查询问题
【发布时间】:2015-02-16 03:47:41
【问题描述】:

有了这个请求:

<?php
$query = '
    SELECT 
        * 
    FROM 
        posts 
    WHERE 
        post_type = "post" AND 
        post_status = "publish" AND 
        post_content LIKE "%'.$search_string.'%" OR 
        post_title LIKE "%'.$search_string.'%"
';

我需要从posts 表中收集所有数据,满足上述条件。

由于没有问题,我将描述我想做的事情。想象一条记录实际上是一个帖子,状态为publish,并且在post_contentpost_title 字段中的请求中有匹配项。

因此,我得到了最后两个操作条件(检查标题中的合规性)。其余的都被忽略了。

【问题讨论】:

  • 什么是问题?你说查询工作正常! :)
  • 问题是“condition1 AND condition2 AND condition3 OR condition 4”被解析器解释为“(c1 and c2 and c3) OR c4”。实际上你想要“ (c1 AND c2) AND (c3 OR c4)”..

标签: php mysql mysqli


【解决方案1】:

使用这个

$query = 'SELECT * FROM posts WHERE (post_type = "post" AND post_status = "publish") AND (post_content LIKE "%'.$search_string.'%" OR post_title LIKE "%'.$search_string.'%")';

【讨论】:

  • 你做了什么?请解释
  • 分组条件,因此它们被评估为括号之间的一个
  • 只需添加括号以使所需条件起作用
【解决方案2】:

只需结合您的 LIKE 子句。

$query = 'SELECT * FROM posts WHERE 
post_type = "post" AND 
post_status = "publish" AND (post_content LIKE "%'.$search_string.'%" OR 
post_title LIKE "%'.$search_string.'%")';

您需要组合 OR 表示两列值的组合。

【讨论】:

    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多