Search code examples
phpmysqlmysql-real-escape-string

mysql real escape string with LIKE not fetching any result


I have a mysql query

mysql_query("SELECT name,symbol FROM scode WHERE change='$change' 
AND product='$product' AND series='$typeo' 
AND (name LIKE '%$check%' OR symbol LIKE '%$check%') LIMIT 5");

It works Perfectly but If I try to use the same query using mysql string then query is not returning any result. i tried like this

$query= sprintf("SELECT name,symbol FROM `scode` WHERE change='%s' 
AND product='%s' AND series='%s' AND (name LIKE '%s' OR symbol LIKE '%s') 
LIMIT 5",
mysql_real_escape_string($change),
mysql_real_escape_string($product),
mysql_real_escape_string($typeo),
mysql_real_escape_string($check),
mysql_real_escape_string($check));

$fetch= mysql_query($query);

How can I make the query that will work? Can some help me? Thanks.


Solution

  • Well no it wouldn't work, because in the first you do a LIKE %term%, in the second you do a LIKE term. Try adding %% around, like this:

    $query= sprintf("SELECT name,symbol FROM `scode` WHERE change='%s' AND product='%s' AND series='%s' AND (name LIKE '%%%s%%' OR symbol LIKE '%%%s%%') LIMIT 5",mysql_real_escape_string($change),mysql_real_escape_string($product),mysql_real_escape_string($typeo),mysql_real_escape_string($check),mysql_real_escape_string($check));
    
    $fetch= mysql_query($query);