Php 问号占位符

Php 问号占位符,php,replace,sqlbuilder,Php,Replace,Sqlbuilder,如何替换所有的“?”变量?比如: $name = 'test' ; $lname = 'lastTest'; $id = 1 ; ->where ( 'customers.name = ? and customers.lastname = ? and customers.id = ?' , $name , $lname , $id ) ; 输出: customers.name='test'和customers.lastname='lastest'和customer

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

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

customers.name='test'和customers.lastname='lastest'和customers.id=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;
}

我真的认为您应该使用像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;
}

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

$name = "'test'";
$lname = "'lastTest'";
$id = 1;
$sql = sprintf('customers.name = %s and customers.lastname = %s and customers.id = %d' , 
                $name , $lname , $id ) ;
请注意,printf语法支持占位符转义,这是一种罕见但可能的情况,您需要在查询中添加文字占位符符号


然而,对于实际使用,我将实现类型化占位符,允许您添加不同类型的数据-标识符、数组等等,对于这样的原始替换,您可以使用标准的printf语法

$name = "'test'";
$lname = "'lastTest'";
$id = 1;
$sql = sprintf('customers.name = %s and customers.lastname = %s and customers.id = %d' , 
                $name , $lname , $id ) ;
请注意,printf语法支持占位符转义,这是一种罕见但可能的情况,您需要在查询中添加文字占位符符号


然而,对于实际使用,我将实现类型化占位符,允许您添加不同类型的数据-标识符、数组等

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

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

$modifiedQuery = str_replace($params, $actualParams, $query);

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

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

$modifiedQuery = str_replace($params, $actualParams, $query);

老实说,我不知道PDO,但准备好的语句已经在mysqli中为您实现了这一点,这是一个选项吗?

老实说,我不知道PDO,但准备好的语句已经在mysqli中为您实现了这一点,这是一个选项吗?

您为此使用了什么库?没有,这是我的框架。您为什么需要它?您是在为数据库实现自己的占位符系统还是什么?你不能更具体一点吗?是的,我正在实现sqlstatements@Basiclife好吧,如果PDO在默认情况下执行字符串连接/操作-这不意味着PDO中有漏洞吗?你用什么库来实现这个?没有,这是我的框架。你为什么需要它?您是在为数据库实现自己的占位符系统还是什么?你不能更具体一点吗?是的,我正在实现sqlstatements@Basiclife好吧,如果PDO在默认情况下执行字符串连接/操作-这不意味着PDO中有漏洞吗?准备好的语句的可用性非常有限,比如说,对于SET运算符,您必须编写自己的小程序。而且根本没有标识符占位符。例如,对于SET运算符,您必须编写自己的小程序。而且根本没有标识符占位符。等等