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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0