请考虑使用bindValue而不是传递数组来执行。正如它所说here:
所有值都被视为 PDO::PARAM_STR。
应该可以使这对应用程序的其余部分非常透明,因为您已经拥有想要以数组形式更新的值。尝试例如像这样的东西:
<?php
function executeWithDataTypes(PDOStatement $sth, array $values) {
$count = 1;
foreach($values as $value) {
$sth->bindValue($count, $values['value'], $values['type']);
$count++;
}
return $sth->execute();
}
$sth = $handle->prepare("UPDATE table SET name = ?, id_extra1 = ?, id_extra2 = ? WHERE id_something = ?");
$values = array();
$values[] = array('value' => 'testing', 'type' => PDO::PARAM_STR);
$values[] = array('value' => 2, 'type' => PDO::PARAM_INT);
$values[] = array('value' => null, 'type' => PDO::PARAM_NULL);
$values[] = array('value' => 1958, 'type' => PDO::PARAM_INT);
$result = executeWithDataTypes($sth, $values);
?>
正如您指出的那样,使用 bindParam 过去会让您感到头疼,请注意两者之间的细微差别绑定值 and 绑定参数。就我个人而言,我从不使用bindParam,因为副作用使得理解脚本变得更加困难,尽管当然在某些情况下这些效果会派上用场。
编辑:您当然可以进一步简化函数,并通过执行以下操作来消除将类型指定为传递数组中的附加键的需要:
$type = PDO::PARAM_STR;
switch(true) {
case is_null($value): $type = PDO::PARAM_NULL; break;
case is_numeric($value): $type = PDO::PARAM_INT; break;
// ...
default: break;
}
并根据数组中传入的值的类型确定类型;然而,这更容易出错,因为例如浮点数也是数字,这会导致上述 switch 语句中的错误决定,但我想为了完整性而提及它。