Skip to content Skip to sidebar Skip to footer

How To Apply Wildcard In Instr() In Mysql?

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()); B

Solution 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.

Solution 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 recordselse$whereclause = "where instr(tag, '$tag') > 0";

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

Post a Comment for "How To Apply Wildcard In Instr() In Mysql?"