How to replace all char events with elements from an array?

I have the following line:

$sql = sql_prepare("UPDATE `test` SET `item1` = ?, `item2` = ?, `item3` = ?", array(50, 55, 60)); 

I need to create a sql_prepare function that will match all the events '?' char and replace with elements from the array, so the final sql will be:

 UPDATE `test` SET `item1` = 50, `item2` = 55, `item3` = 60 

How can i do this?

+1
source share
2 answers

Why try to fake a prepared statement with the deprecated mysql_ * API when both mysqli and PDO implement real prepared statements?

PDO example:

 if ($prepped = $pdo -> prepare ('UPDATE `test` SET `item1` = ?, `item2` = ?, `item3` = ?')) { $res = $prepped -> execute (array (50, 55 ,60)); } 
0
source

for such a simple replacement you can use the sprintf format:

 $sql = vsprintf("UPDATE `test` SET `item1` = %d, `item2` = %d, `item3` = %d", array(50, 55, 60)); 

however, for use in real life it is better to make different types of placeholders

here is the code from my db class

 private function prepareQuery($args) { $raw = $query = array_shift($args); preg_match_all('~(\?[az?])~',$query,$m,PREG_OFFSET_CAPTURE); $pholders = $m[1]; $count = 0; foreach ($pholders as $i => $p) { if ($p[0] != '??') { $count++; } } if ( $count != count($args) ) { throw new E_DB_MySQL_parser("Number of args (".count($args).") doesn't match number of placeholders ($count) in [$raw]"); } $shift = 0; $qmarks = 0; foreach ($pholders as $i => $p) { $pholder = $p[0]; $offset = $p[1] + $shift; if ($pholder != '??') { $value = $args[$i-$qmarks]; } switch ($pholder) { case '?n': $value = $this->escapeIdent($value); break; case '?s': $value = $this->escapeString($value); break; case '?i': $value = $this->escapeInt($value); break; case '?a': $value = $this->createIN($value); break; case '?u': $value = $this->createSET($value); break; case '??': $value = '?'; $qmarks++; break; default: throw new E_DB_MySQL_parser("Unknown placeholder type ($pholder) in [$raw]"); } $query = substr_replace($query,$value,$offset,2); $shift+= strlen($value) - strlen($pholder); } $this->lastquery = $query; return $query; } 

I have to admit that escape ? means that the solution is not elegant, but with what I still have.

-one
source

All Articles