Spinstaz
Spinstaz

Reputation: 331

Hash Password in PHP not a string after retrieval from MYSQL database

I have the password for the login part, which uses $hash = password_hash($password, PASSWORD_DEFAULT);

The password is stored in the database as a hash, $2y$10$CaQON5WOEHcla58aBoIRKOmyYLBwtDHKFqk81y25.EGvjBqlF0W1W

I query the database on the login page and check that the user email is in the database, which it is.

I have checked in MySQL workbench if the query I used works, and it returns the password fine.

However, when I try to query the database for the password and assign it to a variable, I get an error when echoing that the variable is not a string.

I've tried $verify = password_verify($password, $hash); however, the error I also get is parameter 2 must be a string.

So why is the value not a string after I get it? and how do I retrieve the correct value?

Here is my query:

   $sql_e2 = "SELECT password FROM users WHERE email='$email'";
   $hash = mysqli_query($mysqli, $sql_e2);

Thanks

Upvotes: 0

Views: 358

Answers (1)

Spinstaz
Spinstaz

Reputation: 331

I finished putting together what is now working and tested against working & non working accounts.

//query SQL for password
$sql_e2 = $mysqli->prepare("SELECT password FROM users WHERE email = ?");
$sql_e2->bind_param("s", $email);
$sql_e2->execute();
$result = $sql_e2->get_result();

//fetch row from result and assign value
$row = mysqli_fetch_row($result);
$hash = $row[0] ?? false;

// Print the result depending if they match
if (password_verify($password, $hash)) {
    echo 'Password Verified!';
} else {
    echo 'Incorrect Password!';
}

Thanks for the pointers guys.

Upvotes: 2

Related Questions