Skip to content

Instantly share code, notes, and snippets.

@terrymun
Last active April 30, 2018 03:30
Show Gist options
  • Save terrymun/39b001c073b0c31a3ea9 to your computer and use it in GitHub Desktop.
Save terrymun/39b001c073b0c31a3ea9 to your computer and use it in GitHub Desktop.
The difference between bindParam() and bindValue()
<?php
// Assuming that database connection is already open
// Get username
$username = 'johndoe';
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE user = :username");
$stmt->bindParam(':username', $username);
$username = 'janesmith';
$stmt->execute();
// Statement will be executed using 'janesmith' as the username...
// because :username searches for $username upon execution, and
// the last known value of $username is 'janesmith'
?>
<?php
// Assuming that database connection is already open
// Get username
$username = 'johndoe';
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE user = :username");
$stmt->bindValue(':username', $username);
$username = 'janesmith';
$stmt->execute();
// Statement will be executed using 'johnsmith' as the username...
// because the literal value "johndoe" has been bound to :username
// prior to the bindValue() function. Further changes to $username
// will not be reflected in the prepared statement.
?>
@yesitisme
Copy link

you have a mistake the second example should be johndoe not johnsmith.

 $stmt->bindValue(':username', $username);
  $username = 'janesmith';
  
  $stmt->execute();
  // Statement will be executed using 'johndoe' as the username...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment