MySQL LIKE + php sprintf

大兔子大兔子 提交于 2020-01-01 04:20:10

问题


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

回答1:


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




回答2:


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




回答3:


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;



回答4:


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:


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

echo $test;


来源:https://stackoverflow.com/questions/3863199/mysql-like-php-sprintf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!