2012-01-11 58 views
0

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

+0

您可能希望检查['func_get_args'](http://php.net/func_get_args),['func_get_arg'](http://php.net/func_get_arg )和['func_num_args'](http://php.net/func_num_args),但是你必须解析查找'%like'占位符的查询字符串,它可能会干扰你想要使用'name LIKE'%foo%'查询。 – 2012-06-19 11:19:43

+0

非常可行,被低估的问题......这是一个耻辱的答案是无用的,虽然:(你有没有找到你的问题的解决方案? – 2013-11-25 19:24:09

回答

0

sprintf()

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

非常重要的是,你在$_GET消毒的一切,你使用它之前!

+0

db_query的全部重点不是消毒所有的东西,例如,db_query('select * where name =%q',“'and 1 = 1 - ”);将产生select *,其中name ='\'和1 = 1 - '。具有这样一个名称的页面显然不存在,所以查询将会执行无害。 – lamefun 2012-01-11 20:19:04

2

我很困惑... (s)printf说白了媒体链接存在,你可能想使用SQLite3Stmt::bindValue更多对于这一点,除非你想逃脱/ SQL注入地狱结束了..

0

好的,因为我有完全相同的问题,所以我给了它一个镜头,它似乎很好地工作。

下面的函数位于一个数据库包装类的内部,并期望被称为如printf,其中%%被变换为文字%,%e标记字符串参数转义,和%u标志着一个字符串参数采取原样是。

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

注意:代码大部分是未经测试的,很可能是,它包含一堆bug。请谨慎使用:)

相关问题