我经常看到使用bindParam
或bindValue
与PDO的代码。 仅仅将论点传递给execute
会因为任何原因而皱眉吗?
我知道bindParam
实际上绑定到变量,并且您可以使用两种bind
方法设置绑定的参数类型,但是如果您只插入字符串怎么办?
$query = "SELECT col1 FROM t1 WHERE col2 = :col2 AND col3 = :col3 AND col4 = :col4";
$pdo->bindValue(':col2', 'col2');
$pdo->bindValue(':col3', 'col3');
$pdo->bindValue(':col4', 'col4');
我经常看到以上内容,但我个人更喜欢:
$pdo->execute(array(':col2' => 'col2', ':col3' => 'col3', ':col4' => 'col4'));
它没有那么冗长和直观,对我来说,将输入"一起进入"查询更有意义。 但是,我几乎从未见过它被使用过。
当您不必利用前者的特殊行为时,是否有理由更喜欢bind
方法而不是传递参数execute
?
只想将变量引用绑定到查询中的参数时,您可能会发现使用了bindParam
,但可能仍然需要对其进行一些操作,并且只希望在查询执行时计算变量的值。它还允许您执行更复杂的操作,例如将参数绑定到存储过程调用,并将返回的值更新为绑定变量。
有关详细信息,请参阅 bindParam 文档、绑定值文档和执行文档。
例如
$col1 = 'some_value';
$pdo->bindParam(':col1', $col1);
$col1 = 'some_other_value';
$pdo->execute(); // would use 'some_other_value' for ':col1' parameter
bindValue
并将数组传递给execute
的行为方式与参数值在该点固定并相应地执行 SQL 的方式大致相同。
按照上面的相同示例,但使用 bindValue
$col1 = 'some_value';
$pdo->bindValue(':col1', $col1);
$col1 = 'some_other_value';
$pdo->execute(); // would use 'some_value' for ':col1' parameter
直接传入execute
时,所有值都被视为字符串(即使提供了整数值(。 因此,如果您需要强制使用数据类型,则应始终使用 bindValue
或 bindParam
。
我想您可能会看到bind*
使用超过execute(array)
,因为许多人认为在参数声明中显式定义数据类型是更好的编码实践。
通过将参数与 $pdo->execute()
方法一起传递,数组中的所有值都将传递,PDO::PARAM_STR
到 $pdo->bindParam()
函数的语句中。
我现在可以看到的主要区别是,使用 $pdo->bindParam()
函数,您可以使用 PHP.net 手册中所述的PDO::PARAM_*
常量定义传递的数据类型
简单,bindParam 的值可能会改变,但 bindValue 的值不能改变。例:
$someVal=10;
$someVal2=20;
/* In bindParam, the value argument is not bound and
will be changed if we change its value before execute.
*/
$ref->bindParam(':someCol',$someVal);
$someVal=$someVal2;
$ref->execute();
//someCol=20
/* In bindValue, the value argument is bound and
never changed if we change its value before execute.
*/
$ref->bindValue(':someCol',$someVal);
// here assignment is referral (&$someVal)
$someVal=$someVal2;
$ref->execute();
//someCol=10