1

我怎样才能替换所有'?变量?就像是:

   $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

有任何想法吗?

4

4 回答 4

5

我真的认为你应该使用像 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;
}
于 2011-12-11T13:38:35.087 回答
1

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

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

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

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

于 2011-12-11T13:40:26.540 回答
1

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

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

$modifiedQuery = str_replace($params, $actualParams, $query);
于 2011-12-11T13:49:30.137 回答
0

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

于 2011-12-11T16:18:23.963 回答