Question mark placeholder

人盡茶涼 提交于 2020-01-02 23:08:16

问题


How can I replace all '?' the variables? Something like:

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

output:

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

Any ideas?


回答1:


I really think you should use a library like PDO, but here is a solution nonetheless:

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:


well, for such a primitive substitutions you can use standard printf syntax.

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

Note that printf syntax supports placeholder escaping for such a rare yet possible case when you will have to add a literal placeholder symbol into query.

However, for the real life usage I'd implement typed placeholders, letting you add different kind of data - identifiers, arrays and such




回答3:


// ModifiedQuery variable stores your expected format.

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

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



回答4:


I don't know PDO to be honest, but prepared statements do this for you already with mysqli, would this be an option?



来源:https://stackoverflow.com/questions/8464335/question-mark-placeholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!