【问题标题】:MySQL LIKE + php sprintfMySQL LIKE + php sprintf
【发布时间】:2010-10-05 11:29:18
【问题描述】:
$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%'

【问题讨论】:

    标签: php mysql printf sql-like


    【解决方案1】:
    ... LIKE '%%%s%%'", mysql_real_escape_string('test'));
    

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

    【讨论】:

    • 谢谢。这对我有帮助。
    【解决方案2】:

    试试:

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

    sprintf中,如果你想得到%的符号,你必须插入%%。所以第一个通配符%%%,字符串本身是%s,最后一个通配符%%%

    【讨论】:

      【解决方案3】:

      你需要用百分号%%转义百分号。

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

      【讨论】:

        【解决方案4】:

        你在混淆上下文。为保持一致性,将不在 SQL 单引号内的内容放在 sprintf() 格式字符串之外:

        $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;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-04-09
            • 2011-06-22
            • 2012-03-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多