MySQL LIKE + php sprintf

2019-03-24 21:49发布

$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%'

5条回答
贪生不怕死
2楼-- · 2019-03-24 22:27
... 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.

查看更多
Emotional °昔
3楼-- · 2019-03-24 22:33

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;
查看更多
小情绪 Triste *
4楼-- · 2019-03-24 22:37

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") . "%"
        );
查看更多
相关推荐>>
5楼-- · 2019-03-24 22:39

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 %.

查看更多
祖国的老花朵
6楼-- · 2019-03-24 22:50
$test = "SELECT * FROM `table` WHERE `text` LIKE '%s%'" . mysql_real_escape_string('test');

echo $test;
查看更多
登录 后发表回答