Marcel Haidacher Marcel Haidacher - 1 year ago 53
PHP Question

Hash Password in PDO Error/Notice

If I run this I get the following error:

Notice: Only variables should be passed by reference in /var/www/interface/register.php on line 11

I dont know how to fix that. It's still successful and the data is hashed in the database, but I don't want this notice.

$sql = " INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $conn->prepare($sql);

$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

if ($stmt->execute()) :

Thanks in advance.

Answer Source

You cannot do password_hash($_POST['password'], PASSWORD_BCRYPT) inside bindParam, because password_hash returns a string, do:

$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);

If you wish to leave the values there use bindValue:

$stmt->bindValue(':username', $_POST['username']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));

because it allows varibles by reference.


bindParam expects a variable or const it can't be a primitive type such as a string or an int, ..., explicitly (ex: "some_hardcoded_string") neither can it be a function that returns one of this types.

bindValue can receive references and primitive types as an argument.

Examples for both:

$query->bindParam(':user', $user, PDO::PARAM_STR);

$query->bindValue(':pass', sha1($password), PDO::PARAM_STR);

SHA1 is returns a value, it could be a number 12345 (let's say for the sake of the example)

$query->bindValue(':pass', 12345, PDO::PARAM_STR); 

or a string.

$query->bindValue(':pass', 'hashed_password', PDO::PARAM_STR);

retated questions: