2009-12-15 24 views
0

使用通配符,以便所有記錄匹配。如何在MySQL的instr()中應用通配符?

我的代碼:

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

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

但它返回結果爲零。 即使

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

它仍然返回零結果。如何解決這個問題?

回答

1

INSTR不支持通配符。

如果你想在一個MySQL查詢中使用通配符,你將不得不使用一個支持它的功能,如LIKEREGEXP,即:

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

上面的查詢會爲任意值工作的$tag。空白值(空字符串)將返回所有記錄。一定要妥善處理你的$tag值。

0

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