【问题标题】:How to apply wildcard in instr() in MySQL?如何在 MySQL 的 instr() 中应用通配符?
【发布时间】:2009-12-15 04:13:51
【问题描述】:

使用通配符,以便匹配所有记录。

我的代码:

if(empty($tag))
{
$tag="%";
}

mysql_query("select * from mytable where instr(tag,'$tag')>0") or die(mysql_error());

但它返回零结果。 即使

 if(empty($tag))
    {
    $tag="*";
    }

它仍然返回零结果。如何解决这个问题?

【问题讨论】:

    标签: php sql mysql wildcard


    【解决方案1】:

    INSTR 不支持通配符。

    如果要在 MySQL 查询中使用通配符,则必须使用支持它的函数,例如 LIKEREGEXP,即:

    mysql_query("select * from mytable where tag LIKE '%$tag%'")
    

    上述查询适用于$tag 的任何值。空值(空字符串)将返回所有记录。确保您也正确清理了您的 $tag 值。

    【讨论】:

      【解决方案2】:

      首先,instr(及其对应的locate)不识别通配符或任何其他特殊表达式——只能识别文字字符串。处理此问题的常用方法是相应地修改 SQL:

      if (empty($tag))
           $whereclause = "";  // match all records
      else $whereclause = "where instr(tag, '$tag') > 0";
      
      mysql_query("select * from mytable $whereclause") or die(mysql_error());
      

      【讨论】:

        猜你喜欢
        • 2019-05-26
        • 1970-01-01
        • 2017-06-12
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 2023-03-09
        • 2017-02-05
        • 1970-01-01
        相关资源
        最近更新 更多