Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Passing by Reference using a PreparedStatement PHP

Tags:

php

pdo

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!

like image 321
Vidalia Avatar asked Apr 26 '26 01:04

Vidalia


1 Answers

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();
}
like image 57
danzeer Avatar answered Apr 28 '26 14:04

danzeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!