使用 PDO 预处理语句时,bindParam 需逐个绑定变量引用,参数数量不固定时很不方便。bindVars 通过 call_user_func_array 实现动态绑定,自动推断类型(整数/浮点/字符串/Blob)。
<?php
private function bindVars($stmt, $params) {
if ($params === null) return $stmt;
$types = '';
$bind_names = array();
// 1. 构建类型字符串
foreach ($params as $param) {
if (is_int($param)) $types .= 'i';
elseif (is_float($param)) $types .= 'd';
elseif (is_string($param)) $types .= 's';
else $types .= 'b'; // blob/其他
}
$bind_names[] = $types; // 第一个参数必须是类型字符串
// 2. 创建变量引用数组
for ($i = 0; $i < count($params); $i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i]; // 变量变量赋值
$bind_names[] = &$$bind_name; // 引用入数组
}
// 3. 动态调用 bind_param
call_user_func_array(array($stmt, 'bind_param'), $bind_names);
return $stmt;
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$stmt = $pdo->prepare('INSERT INTO users (name, age, score, bio) VALUES (?, ?, ?, ?)');
$params = array('张三', 25, 98.5, '程序员');
bindVars($stmt, $params);
$stmt->execute();
PDOStatement::execute() 直接接受数组参数,无需手动 bind:
$stmt->execute($params); // 自动按字符串绑定,兼容性最好
仅当需要显式指定类型(如 PDO::PARAM_INT 避免数字被加引号)时才需手动绑定。
| PHP 类型 | PDO 常量 | bind_param 字符 |
|---|---|---|
| integer | PDO::PARAM_INT | i |
| float/double | PDO::PARAM_STR | d |
| string | PDO::PARAM_STR | s |
| bool | PDO::PARAM_BOOL | i (0/1) |
| null | PDO::PARAM_NULL | b |
| resource/stream | PDO::PARAM_LOB | b |