14
$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%'
MPelletier
  • 16,256
  • 15
  • 86
  • 137

5 Answers5

45
... 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
  • 337,827
  • 72
  • 505
  • 443
4

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
  • 207,213
  • 34
  • 299
  • 261
1

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
  • 15,438
  • 7
  • 38
  • 49
1

You’re jumbling contexts. For consistency, put the things that aren't inside the SQL single quotes outside of the sprintf() format string:

$test = sprintf(
          "SELECT * FROM `table` WHERE"
            . "`xt` LIKE '%s'",
          "%" . mysql_real_escape_string("test") . "%"
        );
danorton
  • 11,804
  • 7
  • 44
  • 52
0
$test = "SELECT * FROM `table` WHERE `text` LIKE '%s%'" . mysql_real_escape_string('test');

echo $test;
NullUserException
  • 83,810
  • 28
  • 209
  • 234
Steve Claridge
  • 10,650
  • 8
  • 33
  • 35