Php 如何在MySQL的instr()中应用通配符?

Php 如何在MySQL的instr()中应用通配符?,php,sql,mysql,wildcard,Php,Sql,Mysql,Wildcard,使用通配符以便匹配所有记录 我的代码: if(empty($tag)) { $tag="%"; } mysql_query("select * from mytable where instr(tag,'$tag')>0") or die(mysql_error()); 但它返回零结果。 即使 它仍然返回零结果。如何解决此问题?首先,instr(及其对应的locate)不识别通配符或任何其他特殊表达式,只识别文字字符串。处理此问题的通常方法是相应地修改SQL: if (empty($t

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

我的代码:

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

mysql_query("select * from mytable where instr(tag,'$tag')>0") or die(mysql_error());
但它返回零结果。 即使


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

首先,
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());

INSTR
不支持通配符

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

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

if (empty($tag))
     $whereclause = "";  // match all records
else $whereclause = "where instr(tag, '$tag') > 0";

mysql_query("select * from mytable $whereclause") or die(mysql_error());
mysql_query("select * from mytable where tag LIKE '%$tag%'")