MySQL LIKE + php sprintf

user317005 picture user317005 · Oct 5, 2010 · Viewed 16.4k times · Source
$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%s%'", mysql_real_escape_string('test'));

echo $test;

output:

SELECT * FROM `table` WHERE `text` LIKE '%s

but it should output:

SELECT * FROM `table` WHERE `text` LIKE '%test%'

Answer

Daniel Vassallo picture Daniel Vassallo · Oct 5, 2010
... LIKE '%%%s%%'", mysql_real_escape_string('test'));

To print the % character you need to escape it with itself. Therefore the first two %% will print the % character, while the third one is for the type specifier %s. You need a double %% at the end as well.