PDO bindParam 与 bindValue 的区别

bindParam vs bindValue

PDOStatement::bindParam 与 PDOStatement::bindValue不同, 变量被以引用方式绑定到点位符上而且仅仅当调用PDOStatement::execute()时才会去计算具体被绑定变量在PDOStatement::execute()被调用时的值.

So, for example:

1
2
3
4
5
6
<?php
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // 将执行 WHERE sex = 'female'

or

1
2
3
4
5
6
<?php
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // 将执行 WHERE sex = 'male'

来源于Stackoverflow: What is the difference between bindParam and bindValue?