PDO pass by reference notice?

大兔子大兔子 提交于 2019-12-18 05:53:42

问题


This:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindParam(':color', $someClass->getColor());
$stmt->execute();

yields this:

Runtime notice
Only variables should be passed by reference

though it still executes.

This:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = $someClass->getColor();
$stmt->bindParam(':color',$tempColor);
$stmt->execute();

runs without complaint.

I don't understand the difference?


回答1:


The second parameter of bindParam is a variable reference. Since a function return cannot be referenced, it fails to strictly meet the needs of the bindParam parameter (PHP will work with you though and will only issue a warning here).

To get a better idea, here's and example: this code will produce the same results as your second example:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = NULL; // assigned here
$stmt->bindParam(':color',$tempColor);
$tempColor = $someClass->getColor(); // but reassigned here
$stmt->execute();

That won't be possible with a function return.




回答2:


The description of PDOStatement::bindParam() states that it binds a PHP variable to a quesitonmark or named placeholder. Since you are trying to pass a class's method (even though that method does return a value) it is still not a variable name, hence the warning. You might want to look at PDOStatement::bindValue() to future-proof your code.




回答3:


If you want to avoid assigning the value to a variable, you might be better off trying:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = ?");
$stmt->execute(array($someClass->getColor()));

As others have mentioned, the error is caused because PDO::statement->bindParam expects param 2 to be a variable passed by reference.




回答4:


If you really want to bind a value instead of a reference, you can use the PDOStatement::bindValue and then you code would look something like this:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindValue('color', $someObject->getColor());
$stmt->execute();


来源:https://stackoverflow.com/questions/6770850/pdo-pass-by-reference-notice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!