Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between bindParam and bindValue?

What is the difference between PDOStatement::bindParam() and PDOStatement::bindValue()?

like image 863
koen Avatar asked Jul 24 '09 20:07

koen


People also ask

What is bindValue?

The bindValue() function binds a value to a named or question mark in the SQL statement. The bindValue() function is used to pass both value and variable.

What is PDO :: Param_str?

PDO::PARAM_STR. Represents the SQL CHAR, VARCHAR, or other string data type. integer. PDO::PARAM_LOB. Represents the SQL large object data type.


2 Answers

From the manual entry for PDOStatement::bindParam:

[With bindParam] Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

So, for example:

$sex = 'male'; $s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex'); $s->bindParam(':sex', $sex); // use bindParam to bind the variable $sex = 'female'; $s->execute(); // executed with WHERE sex = 'female' 

or

$sex = 'male'; $s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex'); $s->bindValue(':sex', $sex); // use bindValue to bind the variable's value $sex = 'female'; $s->execute(); // executed with WHERE sex = 'male' 
like image 136
lonesomeday Avatar answered Nov 30 '22 00:11

lonesomeday


Here are some I can think about :

  • With bindParam, you can only pass variables ; not values
  • with bindValue, you can pass both (values, obviously, and variables)
  • bindParam works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) :

support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.

like image 37
Pascal MARTIN Avatar answered Nov 30 '22 01:11

Pascal MARTIN