0

Edit: My issue has been resolved. I did not know or think of bindValue(), that is why I do not think this is a duplicate question. Thanks for the help!

I am learning how to register users with PHP and it seems like password_hash is giving me the "Only Variables should be passed by reference" error message. I've seen many people with the same error, but it does not seem to apply to my case (in my opinion).

connecting to database

$server = 'localhost';
$username ='root';
$password ='root';
$database = 'register_test';

try{
    $conn = new PDO("mysql:host=$server;dbname=$database;" , $username, $password);
} catch(PDOException $e){
    die ("Connection failed" . $e->getMessage());
}

Registering user

require 'database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):

$pass = $_POST['password'];
$email = $_POST['email'];

$sql = "Insert into user (email, password) values (:email, :password)";
$stmt = $conn->prepare($sql);

$stmt ->bindParam(':email', $email);
$stmt ->bindParam(':password', password_hash($pass, PASSWORD_BCRYPT)); //error showns here

if($stmt -> execute() ):
  die('Success');
else:
  die('Fail');
endif;
endif;

If you guys need more information please let me know.

Silvio Li
  • 139
  • 1
  • 11
  • Use `$stmt->bindValue()` instead of `$stmt->bindParam()`. – Will Jun 10 '16 at 21:31
  • 1
    Your query won't work anyways. you're specifying one field to insert into, and providing two values. – Marc B Jun 10 '16 at 21:35
  • Marc B. I was trying out a few things and forgot to put 'password' back into the insert statement. Thanks for noticing it – Silvio Li Jun 10 '16 at 21:45

1 Answers1

2

Use PDOStatement::bindValue() instead of PDOStatement::bindParam().

From the docs:

Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

So, your code becomes:

$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', password_hash($pass, PASSWORD_BCRYPT)); 

The result of a function cannot be passed by reference when E_STRICT mode is enabled, without triggering a warning. By using bindValue() instead, we pass the return value of the function as a copy, basically.

Will
  • 24,082
  • 14
  • 97
  • 108
  • Thanks. That did remove the error message, but I do have a new problem. The email and password shows '0' and '0' respectively on the database. – Silvio Li Jun 10 '16 at 21:54
  • No problem, glad to help. Hmm. What does it show if you `var_dump()` `$email` and `$pass`? You might have to post a separate question if it's not something simple. – Will Jun 10 '16 at 22:03
  • var_dump() is showing the correct characters that I input. I recreated the table and it's now working fine. Thanks very much for the help! – Silvio Li Jun 10 '16 at 22:30