dtnrsmi824877 2015-03-18 14:09
浏览 64
已采纳

使用PreparedStatement PHP解释通过引用传递

I have two snippets of code: Take note how the $a variable moves from outside to inside the function call.

$pst = $conn->prepare("INSERT INTO TEST (Num, N, Pos, Team) VALUES (?,?,?,?)");
$a = 99;
$pst->bindParam(1, $a);
$pst->bindParam(2, $a = "badName");
$pst->bindParam(3, $a = "whoCares");
$pst->bindParam(4, $a = "Winning Team");
$pst->execute();

and

$pst = $conn->prepare("INSERT INTO TEST (Num, N, Pos, Team) VALUES (?,?,?,?)");
$pst->bindParam(1, $a = 99);
$pst->bindParam(2, $a = "badName");
$pst->bindParam(3, $a = "whoCares");
$pst->bindParam(4, $a = "Winning Team");
$pst->execute();

This first snippet passes, whereas the second snippet throws the classic Only Variables should be passed by reference Error. Why does this occur? Why does this only occur on the first line - for example this didn't happen on lines 2,3,4 on the first snippet.

EDIT Issue seems similar to this What is the difference between bindParam and bindValue?, but still doesn't explain the cause of error due to the variable being set outside the function call - in either snippet the variable is being set!

  • 写回答

1条回答 默认 最新

  • douyong1885 2015-03-18 15:40
    关注

    bindParam API defined as below:

    boolean PDOStatement::bindParam(mixed parameter,mixed &variable[,int datatype
                                [,int length[,mixed driver_options]]])
    

    pay attention to

    mixed &variable
    

    1 reference should be variables! not constant(like string or number)

    2 when $a was not defined

    value of "$a = 1" was the result of expression : 1 , so the param was 1
    

    after $a was defined, php seems set param to $a (we should digger php's underground machanism- compiling and excuting ) : check code below:

    function test(&$var) {
       //only reference! php will check the param
       echo $var;
    }
    try {
       test($a=1);// report  Only Variables should be passed by reference Error
       unset($a);  // delete $a
       test($a=2);// report again !
    } catch (Exception $e) {
       echo $e->getMessage();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?