Question mark placeholder

2.5k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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
On

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

0
On

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

0
On

// 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);