3

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!

Community
  • 1
  • 1
Vidalia
  • 33
  • 5

1 Answers1

1

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();
}
danzeer
  • 86
  • 6