Search code examples
phppdobindparambindvalue

What is the difference between bindParam and bindValue?


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


Solution

  • The answer is in the documentation for bindParam:

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

    And execute

    call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

    Example:

    $value = 'foo';
    $s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
    $s->bindParam(':baz', $value); // use bindParam to bind the variable
    $value = 'foobarbaz';
    $s->execute(); // executed with WHERE baz = 'foobarbaz'
    

    or

    $value = 'foo';
    $s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
    $s->bindValue(':baz', $value); // use bindValue to bind the variable's value
    $value = 'foobarbaz';
    $s->execute(); // executed with WHERE baz = 'foo'