如果你已经问过了,我很抱歉。我已经看到了关于静态sql的答案,但是在本例中,我想使用PDO->prepare()来处理在运行时动态构建的查询字符串。
分解成一个简单的例子:
$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
if ($numberParams == 1) {
$TempSQL = $TempSQL . " field1 = '$val1' ";
} else {
$TempSQL = $TempSQL . " field2 = '$val2' ";
$TempSQL = $TempSQL . " AND field3 = '$val3' ";
}
db->query($TempSQL);
如何将其重写为db->prepare()?
我是否也应该动态构建语句->execute(array(':param'=>$var))?
有更好/更整洁的方法吗?
最佳答案
也许是这样的。(未测试)
$TempSQL = "SELECT field1, field2, field3 FROM table WHERE ";
$args=array();
if ($numberParams == 1) {
$TempSQL = $TempSQL . " field1 = :val1"
$args[':val1']=$val1;
} else {
$TempSQL = $TempSQL . " field2 = :val2 and field3 = :val3";
$args[':val2']=$val2;
$args[':val3']=$val3;
}
$stmt=$db->prepare($TempSQL);
$stmt->execute($args);