PDOStatement::bindParam()和PDOStatement::bindValue()之间的区别是什么?


当前回答

你再也不用挣扎了,只要有这样一条路:

$stmt = $pdo->prepare("SELECT * FROM someTable WHERE col = :val");
$stmt->execute([":val" => $bind]); 

其他回答

你再也不用挣扎了,只要有这样一条路:

$stmt = $pdo->prepare("SELECT * FROM someTable WHERE col = :val");
$stmt->execute([":val" => $bind]); 

从PDOStatement::bindParam的手动条目:

与PDOStatement::bindValue()不同的是,该变量被绑定为引用,并且仅在调用PDOStatement::execute()时才会被求值。

举个例子:

$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(); // executed with WHERE sex = 'female'

or

$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(); // executed with WHERE sex = 'male'

来自准备语句和存储过程

使用bindParam插入多行,一次绑定:

<?php

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();

答案在bindParam的文档中:

与PDOStatement::bindValue()不同的是,该变量被绑定为引用,并且仅在调用PDOStatement::execute()时被计算。

和执行

调用PDOStatement::bindParam()将PHP变量绑定到参数标记:绑定的变量将其值作为输入传递,并接收相关参数标记的输出值(如果有的话)

例子:

$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindParam(':baz', $value); // use bindParam to bind the variable
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foobarbaz'

or

$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindValue(':baz', $value); // use bindValue to bind the variable's value
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foo'

最简单的方法是通过行为来进行记忆(在PHP中):

bindParam:参考 bindValue:变量