Home » Differentiate bindParam From bindValue

The main difference between PDOStatement bindParam() and PDOStatement bindValue() is that when using the former, the variable is bound as a reference and will only be evaluated at the time that PDOStatement execute() is called. The value of the parameter can still be changed until the statement is executed, while whatever first set value will always be considered for the later.

Requirements:

  • PHP
  • PHP Data Objects
  • PDO Drivers
  • PDOStatement::bindParam
  • PDOStatement::bindValue

Make sure the connection to MySQL Database have already been successfully made. And assign the connection object to variable $dbh.

Consider below as the employees TABLE inside a MySQL DATABASE.

PDOStatement bindParam() Example.

Use PDOStatement bindParam() with the question mark (?) placeholder, initially bind the variable $firstName to Peter Rick, and then later change the value to Mary Ann.

$firstName = 'Peter Rick'; // will be ignored
$sth = $dbh->prepare(
    "SELECT * FROM employees WHERE first_name = ?"
);
$sth->bindParam(1, $firstName, PDO::PARAM_STR);
$firstName = 'Mary Ann';
$sth->execute();
$result = $sth->fetch();

echo '<pre>';
    print_r($result);
echo '</pre>';

Result:

Array
(
    [id] => 3
    [0] => 3
    [first_name] => Mary-Ann
    [1] => Mary-Ann
    [last_name] => Thomas
    [2] => Thomas
)

Try PDOStatement bindValue() with the named (:name) placeholder, bind first the variable $firstName to Peter Rick, and before PDOStatement::executechange the value to Mary Ann.

$firstName = 'Peter Rick';
$sth = $dbh->prepare(
   "SELECT * FROM employees WHERE first_name = :firstName"
);
$sth->bindValue(':firstName', $firstName, PDO::PARAM_STR);
$firstName = 'Mary Ann'; // will be ignored
$sth->execute();
$result = $sth->fetch();

echo '<pre>';
    print_r($result);
echo '</pre>';

Result.

Array
(
    [id] => 2
    [0] => 2
    [first_name] => Peter-Rick
    [1] => Peter-Rick
    [last_name] => Williams
    [2] => Williams
)

Notes:

  • Always sanitize user inputs.

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *