MySQL LIKE + php sprintf

时间:2010-10-05 11:29:19

标签: php mysql printf sql-like

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

echo $test;

输出:

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

但它应输出:

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

5 个答案:

答案 0 :(得分:38)

... LIKE '%%%s%%'", mysql_real_escape_string('test'));

要打印%字符,您需要将其自身转义。因此,前两个%%将打印%字符,而第三个字符用于类型说明符%s。你最后也需要一个双%%

答案 1 :(得分:3)

尝试:

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

sprintf中,如果您想获得%标志,则必须插入%%。因此,第一个通配符%%%,字符串本身为%s,最后一个通配符%%%

答案 2 :(得分:1)

您需要使用百分号%%来转义百分号。

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

echo $test;

答案 3 :(得分:1)

你是一个喋喋不休的背景。为保持一致性,请将不在SQL单引号内的内容放在 sprintf()格式字符串之外:

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

答案 4 :(得分:0)

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

echo $test;