我有以下字符串:
$sql = sql_prepare("UPDATE `test` SET `item1` = ?, `item2` = ?, `item3` = ?", array(50, 55, 60));
我需要创建“sql_prepare”函数,它将匹配'?'的所有出现char并用数组中的元素替换,所以最终的sql将是:
UPDATE `test` SET `item1` = 50, `item2` = 55, `item3` = 60
我该怎么做?
答案 0 :(得分:0)
当mysqli和PDO都实现真正准备好的语句时,为什么要尝试用遗留的mysql_ * API伪造一个准备好的语句?
PDO示例:
if ($prepped = $pdo -> prepare ('UPDATE `test` SET `item1` = ?, `item2` = ?, `item3` = ?'))
{
$res = $prepped -> execute (array (50, 55 ,60));
}
答案 1 :(得分:-1)
对于这种简单的替换,您可以使用sprintf格式:
$sql = vsprintf("UPDATE `test` SET `item1` = %d, `item2` = %d, `item3` = %d",
array(50, 55, 60));
然而,对于现实生活中的使用,最好制作不同类型的占位符
这是我的db class
中的代码private function prepareQuery($args)
{
$raw = $query = array_shift($args);
preg_match_all('~(\?[a-z?])~',$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;
}
我必须承认逃避?
标记解决方案不是优雅的,但这就是我到目前为止所做的。