Home >Backend Development >PHP Tutorial >bindParam vs. bindValue: What's the Key Difference in PHP's PDO?
Understanding the Distinction between bindParam and bindValue
Question:
What is the fundamental difference between PDOStatement::bindParam() and PDOStatement::bindValue()?
Answer:
According to the PDOStatement::bindParam manual entry, the key distinction lies in the referencing behavior of the two methods. bindParam binds variables as references, whereas bindValue binds the values of variables. This referencing behavior comes into play during the execution of PDOStatement::execute().
bindParam Example:
Consider the following code:
$sex = 'male'; $s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex'); $s->bindParam(':sex', $sex); // bind the variable using bindParam $sex = 'female'; $s->execute(); // execute with WHERE sex = 'female'
Here, bindParam binds $sex as a reference. When the statement executes, it references the current value of $sex, which has changed to 'female'. Therefore, the query will retrieve results for 'female' students.
bindValue Example:
Now let's examine a similar example using bindValue:
$sex = 'male'; $s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex'); $s->bindValue(':sex', $sex); // bind the variable's value using bindValue $sex = 'female'; $s->execute(); // execute with WHERE sex = 'male'
In this case, bindValue binds the value of $sex at the time of binding, which is 'male'. Thus, the query will always retrieve results for 'male' students, even though the value of $sex is changed later. This demonstrates the non-referencing behavior of bindValue.
The above is the detailed content of bindParam vs. bindValue: What's the Key Difference in PHP's PDO?. For more information, please follow other related articles on the PHP Chinese website!