What is the difference between bindParam and bindValue?

16

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

    
asked by anonymous 17.09.2015 / 06:27

3 answers

22

Differences in receiving values:

As per rray quoted:

  

In bindParam () the expected argument is a reference (variable or constant) and can not be a primitive type such as a string or loose number, function / method return. Already bindValue () can get references and values as arguments.

$stmt->bindParam(':v1', 10); // Inválido
$stmt->bindParam(':v1', getValor()); // Inválido


Differences in PDOStatement::execute()

  

With bindParam , unlike bindValue , the variable   is linked to a reference and will only be assessed at the time   PDOStatement :: execute () is called.

With bindParam:

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex);
$sex = 'female';
$s->execute(); // Executado quando $sex = 'female'

With bindValue:

$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex);
$sex = 'female';
$s->execute(); // Executado quando $sex = 'male'

Font

    
19.09.2015 / 21:16
6

No bindParam() the expected argument is a reference (variable or constant) can not be a primitive type such as a string or loose number, function / method return. bindValue() can receive references and values as argument, basically that's it.

The code below returns the error:

  

Fatal error: Can not pass parameter 2 by reference in

$stmt->bindParam(':v1', 10); //inválido
$stmt->bindParam(':v1', getValor()); //inválido
    
17.09.2015 / 06:33
6

See this SELECT I use, at least here is a real and commonly used example, as requested:

The bindParam always use with variables if using a value of type 'user name' instead of the variable will give error because it does not accept value, and bindValue is the I use the same value 'nome do usuário' , 1235456 . I understand so bindParam parameters by reference uses variable, bindValue even direct values without using variable. I may not be right on some points but I hope to help lighten up a bit.

$usuario ='fulano';
$senha = '123456';
$conn = new PDO('mysql:host=localhost;dbname=nome_banco','','');
$query = $conn->prepare("SELECT * FROM usuarios WHERE usuario = :user AND senha = :pass ");
$query->bindParam(':user', $usuario, PDO::PARAM_STR);
#Uso o bindParam quando uso variáveis conforme acima.

$query->bindValue(':pass', sha1($senha), PDO::PARAM_STR);
#E uso bindValue quando vou passar o valor diretamente na classe pdo como está aqui acima.

#o sha1 vai me retornar um valor, como também poderia usar ex: 12345
$query->bindValue(':pass', 12345, PDO::PARAM_STR); 
#ou assim.
$query->bindValue(':pass', 'senha', PDO::PARAM_STR);


$query->execute();
$dados = $query->fetch(PDO::FETCH_ASSOC); 

This example might make it clearer how to use it, I hope you understand.

    
24.09.2015 / 05:15