views:

43

answers:

4
$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%'
+3  A: 
... 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.

Daniel Vassallo
+1  A: 

Try:

$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%%s%%'", mysql_real_escape_string('test'));

In sprintf, if you want to get a % sign, you have to insert %%. So it's %% for the first wildcard %, %s for the string itself and %% for the last wildcard %.

eumiro
A: 
$test = "SELECT * FROM `table` WHERE `text` LIKE '%s%'" . mysql_real_escape_string('test');

echo $test;
Steve Claridge
+1  A: 

You need to escape the percent signs with a percent sign %%.

$test = sprintf("SELECT * FROM `table` WHERE `text` LIKE '%%%s%%'", mysql_real_escape_string('test'));

echo $test;
Ruel