Why do I get “Only variables should be passed by reference” in a prepared statement

那年仲夏 提交于 2019-12-31 05:29:06

问题


I am getting the error "Only variables should be passed by reference" if my code is like this.

$query = "SELECT COUNT(`user_id`) FROM `test` WHERE `username` = ? AND `active` = ?";
$stmt = $this->db->prepare($query);
$stmt->bind_param('si',$username,$active=1);
$stmt->execute();
$stmt->bind_result($count);
if($stmt->fetch()){}
return ($count == 1) ? true : false;

However if I do it this way

$query = "SELECT COUNT(`user_id`) FROM `test` WHERE `username` = ? AND `active` = ?";
$active=1
$stmt = $this->db->prepare($query);
$stmt->bind_param('si',$username,$active);
$stmt->execute();
$stmt->bind_result($count);
if($stmt->fetch()){}
return ($count == 1) ? true : false;

I don't get any error, even though both work correctly. I can't understand why I get the error in the first block of code, but I don't get the error if I put $active=1; before the prepared statement, in the second block of code.

It doesn't make any sense to me. I wonder if somebody can tell me why.


回答1:


The bind parameters function of mysqli is intended to

Binds variables to a prepared statement as parameters

the purpose of which is to protect against sql-injection

in your first code block above you attempting to set the variable inside of the bind_param function and in your second block you are setting the variable before the function call

another method would be to just pass in the value

  $stmt->bind_param('si',$username,1);

though this method will work it does violate the strict interpretation, and may trigger warning and/or errors

It is best to always pass in a variable and avoid potential issues

$active = 1;    
$stmt->bind_param('si',$username,$active);


来源:https://stackoverflow.com/questions/43851473/why-do-i-get-only-variables-should-be-passed-by-reference-in-a-prepared-statem

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