Confirm password PHP, Javascript, HTML

3

I wanted to do the password verification, if the passwords are different then an alert with something like "Passwords do not match" appears, if it did, it would pass through. But the way I'm doing it appears a message from the $ message "The passwords are the same", but still it is sending the data to the bank.

<?php 

    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=nise', $username );

    $query = "INSERT INTO usuario (nome, sobrenome, matricula, email, senha) 
          VALUES (:nome, :sobrenome, :matricula, :email, :senha)";

    $statement = $connection->prepare($query);


    $valores = array();
    $valores[':nome'] = (isset($_POST['primeiroNome']) ? $_POST['primeiroNome'] : '');
    $valores[':sobrenome'] = (isset($_POST['sobrenome']) ? $_POST['sobrenome'] : '');
    $valores[':matricula'] = (isset($_POST['matricula']) ? $_POST['matricula'] : '');
    $valores[':email'] = (isset($_POST['email']) ? $_POST['email'] : '');
    $valores[':senha'] = (isset($_POST['senha']) ? $_POST['senha'] : '');






    $result = $statement->execute($valores);

        if($_POST) {
            $senha          = $_POST['senha'];
            $confirma_senha  = $_POST['confirma_senha'];
            if ($senha == "") {
                $mensagem = "<span class='aviso'><b>Aviso</b>: Senha não foi alterada!</span>";
            } else if ($senha == $confirma_senha) {
                $mensagem = "<span class='sucesso'><b>Sucesso</b>: As senhas são iguais: ".$senha."</span>";
            } else {
                $mensagem = "<span class='erro'><b>Erro</b>: As senhas não conferem!:".$confirma_senha."</span>";
            }
            echo "<p id='mensagem'>".$mensagem."</p>";
        }



    ?>

This part of the script warns if passwords match, if yes it does not give any alerts, if not, a DIFFERENT PASSWORDS alert appears, but when I press "OK" to close the alert the form data is removed and sent to the bank anyway, and that was not to happen

 <script> function validarSenha(){
        senha = document.formulario.senha.value
        confirma_senha = document.formulario.confirma_senha.value
        if (senha == confirma_senha) alert
        else alert("SENHAS DIFERENTES")
        }
   </script>

And here's my form

<form method="POST" action="registro.php" name="formulario">
           <div class="form-group">
              <div class="form-row">
                 <div class="col-md-6">
                    <label for="primeiroNome">Primeiro nome</label>
                    <input type="text" class="form-control" id="primeiroNome" name="primeiroNome" placeholder="Digite seu primeiro nome" required="required">
                 </div>
                 <div class="col-md-6">
                    <label for="Sobrenome">Sobrenome</label>
                    <input type="text" class="form-control" id="Sobrenome" name="sobrenome" placeholder="Digite seu Sobrenome" required="required" autofocus="autofocus">
                 </div>
              </div>
           </div>
           <div class="col-md-6" id="matricula">
              <label for="primeiroNome">Matrícula</label>
              <input type="text" class="form-control"  name="matricula" placeholder="Digite sua matrícula" required="required" autofocus="autofocus">
           </div>
           <div class="form-group">
              <label for="email">E-mail</label>
              <input type="email" class="form-control" id="email" name="email" placeholder="Digite seu email" required="required" autofocus="autofocus">
           </div>
           <div class="form-group">
              <div class="form-row">
                 <div class="col-md-6">
                    <label for="senha">Senha</label>
                    <input type="password" class="form-control" id="senha" name="senha" placeholder="Digite sua senha" required="required" autofocus="autofocus">
                 </div>
                 <div class="col-md-6">
                    <label for="confirma_senha">confirmar senha</label>
                    <input type="password"  class="form-control" id="confirmaSenha" name="confirma_senha" placeholder="Confirme sua senha" required="required" autofocus="autofocus">
                 </div>
              </div>
           </div>
           <div>
              <input type="submit"  onClick="validarSenha()" class="btn btn-primary btn-block" value="Registra-se"/>
           </div>
           <div class="text-center">
              <a href="#" class="d-block small mt-3">Esqueceu sua senha?</a>
              <a href="login.php" class="d-block small mt-3">Login?</a>
           </div>
        </form>

Note: If someone has more beautiful alert suggestions you can send ...

    
asked by anonymous 05.10.2018 / 19:35

1 answer

4

This is happening because you are calling $statement->execute($valores) before the checks. So the records will be entered regardless of what the checks verify. Try to reallocate this code and use it as a condition along with password verification that then the code will behave the way you expect it to. For example:

<?php 

    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=nise', $username );

    $query = "INSERT INTO usuario (nome, sobrenome, matricula, email, senha) 
          VALUES (:nome, :sobrenome, :matricula, :email, :senha)";

    $statement = $connection->prepare($query);


    $valores = array();
    $valores[':nome'] = (isset($_POST['primeiroNome']) ? $_POST['primeiroNome'] : '');
    $valores[':sobrenome'] = (isset($_POST['sobrenome']) ? $_POST['sobrenome'] : '');
    $valores[':matricula'] = (isset($_POST['matricula']) ? $_POST['matricula'] : '');
    $valores[':email'] = (isset($_POST['email']) ? $_POST['email'] : '');
    $valores[':senha'] = (isset($_POST['senha']) ? $_POST['senha'] : '');








        if($_POST) {
            $senha          = $_POST['senha'];
            $confirma_senha  = $_POST['confirma_senha'];
            if ($senha == "") {
                $mensagem = "<span class='aviso'><b>Aviso</b>: Senha não foi alterada!</span>";
            } else if ($senha == $confirma_senha && $statement->execute($valores)) {
                $mensagem = "<span class='sucesso'><b>Sucesso</b>: As senhas são iguais: ".$senha."</span>";

            } else {
                $mensagem = "<span class='erro'><b>Erro</b>: As senhas não conferem!:".$confirma_senha."</span>";
            }
            echo "<p id='mensagem'>".$mensagem."</p>";
        }



    ?>

Note that the success condition is if ($senha == $confirma_senha && $statement->execute($valores)) . Surgeri it thus, joining comparison of passwords with the execution of the statement because when $statement->execute($valores) is done successfully it returns a result booleando true , which will be one of the determinants to supply the condition of if and display the message of success. More details about the statement return in the official documentation: link .

About javascript, change some things, putting boolean returns too, for example:

<script> 
    function validarSenha(){
    senha = document.formulario.senha.value
    confirma_senha = document.formulario.confirma_senha.value
    if (senha == confirma_senha){
        return true
    }
    else{ 
        alert("SENHAS DIFERENTES")
        return false
    }
}

And then remove this function from OnClick of submit and place it as attribute of <form> tag in this way onsubmit="return validarSenha()" , getting form tag similar to that <form method="POST" action="registro.php" onsubmit="return validarSenha()"name="formulario">

    
05.10.2018 / 19:47