What's the difference between PDOStatement :: bindParam () and PDOStatement :: bindValue ()?
What's the difference between PDOStatement :: bindParam () and PDOStatement :: bindValue ()?
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
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'
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
See this SELECT
I use, at least here is a real and commonly used example, as requested:
'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.