这是regexp technique 的通用变体,用于参数编号数组。
这比公认的答案更偏执,因为引用所有内容,包括数字,不止一次地在背后咬了我;在 MySQL 以及其他地方1,'123' 小于 '13'。 'NULL' 也是如此,这 不是 NULL,'false' 显然是 true。
现在有人向我指出,我还没有偏执足够 :-),而我的? 替换技术 ("#\\?#") 是幼稚,因为无论出于何种原因,源查询都可能在正文中包含问号作为文本:
$query = "SELECT CONCAT('Is ', @value, ' ', ?, '? ',
IF(@check != ? AND 123 > '13', 'Yes!', 'Uh, no?'))
;
$values = array('correct', false, 123);
// Expecting valid SQL, selecting 'correct' if check is not false for 123
// and answering Yes if @check is true.
输出:
SELECT CONCAT('Is ', @value, ' ', 'correct', '? ',
IF(check != false AND 123 > '13', 'Yes!', 'Uh, no?'))
;
Is THIS_TEST correct? Yes!
我更简单的实现会抛出一个异常,看到太多问号。一个更简单的实现会返回类似
Is THIS_TEST correcttrue Uh, no
所以这是修改后的功能。 注意:我知道有things regexes shouldn't do。我并不声称此功能适用于所有情况和所有边界情况。我声称这是一个合理的尝试。随意评论或通过电子邮件发送非工作测试用例。
function boundQuery($db, $query, $values) {
$ret = preg_replace_callback(
"#(\\?)(?=(?:[^']|['][^']*')*$)#ms",
// Notice the &$values - here, we want to modify it.
function($match) use ($db, &$values) {
if (empty($values)) {
throw new PDOException('not enough values for query');
}
$value = array_shift($values);
// Handle special cases: do not quote numbers, booleans, or NULL.
if (is_null($value)) return 'NULL';
if (true === $value) return 'true';
if (false === $value) return 'false';
if (is_numeric($value)) return $value;
// Handle default case with $db charset
return $db->quote($value);
},
$query
);
if (!empty($values)) {
throw new PDOException('not enough placeholders for values');
}
return $ret;
}
也可以extend PDOStatement 以提供$stmt->boundString($values) 方法。
(1)既然是PHP,你试过$a = 1...1; print $a;吗?