如何在PHP中实现类似printf的函数?

时间:2012-01-11 20:11:14

标签: php printf

我想为我的数据库抽象创建一个db_queryf函数。它的工作方式有点像SQLite中的sqlite3_mprintfdb_queryf('select * from pages where name=%q', $_GET['name']),其中%q将生成一个正确转义的字符串。在PHP中制作类似printf的函数的正确方法是什么?是否有任何帮助函数,或者我自己应该解析它?

4 个答案:

答案 0 :(得分:2)

我很困惑...... (s)printf显然已经存在,你可能想要更多地使用SQLite3Stmt::bindValue,除非你想最终逃脱/ sql-injection地狱..

答案 1 :(得分:1)

使用PDO prepared statements。替换成字符串不够好,你应该进行消毒。

答案 2 :(得分:0)

sprintf()

sprintf('select * from pages where name=\'%s\'', $_GET['name']);

非常重要,您在使用它之前清理$_GET中的所有内容!

答案 3 :(得分:0)

好吧,既然我有完全相同的问题,我试了一下,看起来效果很好。

以下函数位于数据库包装类中,并且期望像printf一样被调用,其中%%被转换为文字%,%e标记要转义的字符串参数,%u 1}}标记一个字符串参数,按原样。

LOGDB是第二个数据库包装类,负责捕获和记录各种错误。

  public static function query($format)
  {
    $query = $format . ' ';

    $argc = func_num_args();
    $argv = func_get_args();

    $index_query = 0;
    $index_args = 1;

    while (($index_query = strpos($query, '%', $index_query)) !== false)
      {
        switch ($query[$index_query + 1])
          {
          case '%':
            $query = substr_replace($query, '', $index_query, 1);
            $index_query++;
            break;
          case 'e':
            if ($index_args >= $argc)
              {
                LOG::failedQuery($format, "not enough arguments for format");
                return false;
              }
            $query = substr_replace($query, DB::escape($argv[$index_args]), $index_query, 2);
            $index_query += strlen($argv[$index_args]);
            $index_args++;
            break;
          case 'u':
            if ($index_args >= $argc)
              {
                LOG::failedQuery($format, "not enough arguments for format");
                return false;
              }
            $query = substr_replace($query, $argv[$index_args], $index_query, 2);
            $index_query += strlen($argv[$index_args]);
            $index_args++;
            break;
          default:
            LOG::failedQuery($format, "unknown control sequence '%" . $query[$index_query + 1] . "'");
            return false;
          }
      }

    if ($index_args != $argc)
      {
        LOG::failedQuery($format, "too many arguments for format");
        return false;
      }

    $res = mysqli_query(self::$handle, $query);
    if (!$res)
      LOGDB::failedQuery($query, mysqli_error(self::$handle));

    return $res;
  }

注意:代码大多未经测试,可能是,它包含一堆错误。谨慎使用:))

相关问题