How to do encrypted password queries in the database?

0

Well, I created a function called UserSearch that should encrypt the user's password and compare it to the database, but every time I run I get the error:

  

Warning: mysqli_fetch_assoc () expects parameter 1 to be mysqli_result, boolean given in C: \ xampp \ htdocs \ warehouse \ user-bank.php on line 9

Function

function buscaUsuario($conexao, $email, $senha){
    $hash = password_hash($senha, PASSWORD_DEFAULT);
    $query = "select * from usuarios where email='{$email}, senha='{$hash}'";
    $resultado = mysqli_query($conexao, $query);
    $usuario = mysqli_fetch_assoc($resultado);
    if(password_verify($usuario, $hash)){
        echo "Valid";
    } else {
        echo "invalid";
    }
    return $usuario;
 }

How could I make this function compare the hash generated with the hash that is in the database and still confirm if the login was valid or invalid?

I've been thinking of getting my database to return the value registered in the password field by assigning it to a variable so that I can use password_verify($user_senha, $hash) and verify that the hash generated by the user is the same as the one registered in the database. Would it work? If so, how?

    
asked by anonymous 23.07.2017 / 06:11

1 answer

3

Your love seems to have a syntax error.

You're like this:

"select * from usuarios where email='{$email}, senha='{$hash}'";

The correct one would be:

"select * from usuarios where email='{$email} AND senha='{$hash}'";

Taking into account that in the user registry you have stored in your table the hash generated by the password_hash function, the corrected script would look like this:

function buscaUsuario($conexao, $email, $senha){
    $query       = "select * from usuarios where email='".$email."'";
    $resultado   = mysqli_query($conexao, $query);
    $row_cnt     = mysqli_num_rows($resultado);
    if($row_cnt > 0){
        $usuario = mysqli_fetch_assoc($resultado);
        /*$senha é o valor digitado pelo usúario e o $usuario['hash'] salvo 
        anteriormente no banco de dados*/
        if(password_verify($senha, $usuario['hash'])){
            echo "Valid";
            return $usuario;
        }else{
           echo "invalid";
           return false;
       }
    }else{
       echo "Não existem usuários com o login informado.";
       return false;
    }
}

Credits for correction to @Inkeliz, improve and adapt to your liking!

    
23.07.2017 / 06:38