How to apply wildcard in instr() in MySQL?

守給你的承諾、 提交于 2019-12-13 07:30:16

问题


Using a wildcard so all records will be matched.

My code:

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

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

But it returns zero result. Even if

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

It still returns zero result. How to resolve this problem?


回答1:


INSTR does not support wildcards.

If you want to use wildcards in a MySQL query, you'll have to use a function that supports it, such as LIKE or REGEXP, ie:

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

The above query will work for any value of $tag. A blank value (empty string) will return all records. Be sure you properly sanitize your $tag value as well.




回答2:


First of all, instr (and its counterpart locate) do not recognize wildcards or any other special expression—only literal strings. The usual way to handle this is to modify the SQL accordingly:

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

mysql_query("select * from mytable $whereclause") or die(mysql_error());


来源:https://stackoverflow.com/questions/1905119/how-to-apply-wildcard-in-instr-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!