【问题标题】:Question mark placeholder问号占位符
【发布时间】:2011-12-11 13:33:49
【问题描述】:

如何替换所有“?”变量?比如:

   $name = 'test' ;
   $lname = 'lastTest';
   $id = 1 ;
   ->where ( 'customers.name = ? and customers.lastname = ? and customers.id = ?' , $name , $lname , $id ) ;

输出:

customers.name = 'test' and customers.lastname = 'lastTest' and customers.id = 1

有什么想法吗?

【问题讨论】:

  • 你用什么库来做这个?
  • 无,这是我的框架。
  • 你为什么需要那个?您是在为数据库实现自己的占位符系统还是什么?不能再具体点吗?
  • 是的,我正在实现 sql 语句的制造
  • @Basiclife 好吧,如果 PDO 默认进行字符串连接/操作 - 这是否意味着 PDO 中存在 漏洞?

标签: php replace sqlbuilder


【解决方案1】:

我真的认为你应该使用像 PDO 这样的库,但这里有一个解决方案:

public function where($query)
{
    $args = func_get_args();
    array_shift($args);

    $query = preg_replace_callback('/\?/', function($match) use(&$args)
    {
        return array_shift($args); // wrap in quotes and sanitize
    }, $query);

    return $query;
}

【讨论】:

    【解决方案2】:

    // ModifiedQuery 变量存储您期望的格式。

    $query  = "customers.name = ? and customers.lastname = ? and customers.id = ?";
    $params = array("?", "?", "?");
    $actualParams   = array($name, $lname, $id);
    
    $modifiedQuery = str_replace($params, $actualParams, $query);
    

    【讨论】:

      【解决方案3】:

      嗯,对于这样的原始替换,您可以使用标准 printf 语法。

      $name = "'test'";
      $lname = "'lastTest'";
      $id = 1;
      $sql = sprintf('customers.name = %s and customers.lastname = %s and customers.id = %d' , 
                      $name , $lname , $id ) ;
      

      请注意,当您必须在查询中添加文字占位符符号时,printf 语法支持对这种罕见但可能的情况进行占位符转义。

      但是,对于现实生活中的使用,我会实现类型化占位符,让您添加不同类型的数据 - 标识符、数组等

      【讨论】:

        【解决方案4】:

        说实话,我不知道 PDO,但是准备好的语句已经用 mysqli 为你做这件事,这是一个选择吗?

        【讨论】:

        • 准备好的语句的可用性非常有限
        • 说,对于 SET 运算符,您必须编写自己的小程序。并且根本没有标识符占位符。等等。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-25
        • 1970-01-01
        • 2019-05-04
        • 2014-09-03
        • 1970-01-01
        相关资源
        最近更新 更多