为什么我得到“仅变量应通过引用传递"?在准备好的陈述中 [英] Why do I get "Only variables should be passed by reference" in a prepared statement

查看:53
本文介绍了为什么我得到“仅变量应通过引用传递"?在准备好的陈述中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的代码是这样的,我将收到错误消息仅变量应通过引用传递".

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;

但是,如果我这样做

$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;

即使两者都能正常工作,我也没有任何错误. 我不明白为什么在第一段代码中会出错,但是如果我将$ active = 1放到错误中,则不会出错.在准备好的语句之前,在第二个代码块中.

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.

推荐答案

mysqli 用于

变量绑定到准备好的语句作为参数

Binds variables to a prepared statement as parameters

其目的是防止sql-injection

the purpose of which is to protect against sql-injection

在上面的第一个代码块中尝试在bind_param函数内部设置变量,而在第二个代码块中,则在函数调用之前设置变量

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

另一种方法是只传递值

  $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);

这篇关于为什么我得到“仅变量应通过引用传递"?在准备好的陈述中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆