How not to lose filling the form fields, after validation with PHP [duplicate]

0

This question differs from existing questions: persisting / filling in data a form via PHP? and How to pass a value to next page with PHP because my form has between 50 and 100 fields, so a solution using GET or POST is impractical or impractical.

Although my production form has a lot of fields, I'm using the code below with just 2 fields to simplify:

<formclass="form" name="frmCadAcolhido" method="post" action="insert.php">
    <input type="hidden" name="acao" value="inserir" >

            <label class="control-label">Nome</label>
            <input type="text" class="control" name="nome" required>

            <label class="control-label">CPF</label>
            <input type="text" class="control" name="cpf" required maxlength="11">

            <input type="submit" name="btnCadastar" value="Cadastrar">
 </form>

When the user clicks the button, the script in "insert.php" is submitted. First, it checks if the user-entered CPF already exists in the table through a MySQL database query. If the CPF does not exist, an INSERT of the fields in the table is done. But if the CPF already exists, it displays an error message and returns to the form. Here is the php code:

include "Conexao.class.php";

$dados = $_POST;

if($dados['acao'] == 'inserir')
{
    $conn = new Conexao();
    $conn->conectaBase();

    $cpf = $dados['cpf'];

    $sql = mysqli_query($conn->link,"SELECT * FROM acolhidos WHERE cpf = '$cpf' ");

    $existecpf = mysqli_num_rows($sql);

    // Se o número do CPF já existe na tabela ACOLHIDOS, retornar mensagem de erro.

    if ($existecpf != 0){
        echo "<script>alert('ERRO: CPF já existe no banco de dados.');</script>";
        echo "<script>history.go(-1)</script>";
    }

    $sql = "INSERT INTO acolhidos
    (
    nome,
    cpf
    )
    VALUES
    (
    '$dados[nome]',
    '$dados[cpf]',
    )";
    $query = mysqli_query($conn->link, $sql);
    echo mysqli_error($conn->link);
}

$conn->desconecta(); 

However, when the script returns to the html form, the contents of all form fields appear empty.

How can I do that, when I return to the form, the data entered by the user is still filled?

The echo "<script>history.go(-1)</script>"; command returns to the form page, but with empty fields.

    
asked by anonymous 29.03.2018 / 00:11

2 answers

1

In PHP, if you already have the CPF, direct the php redirection by passing the data to get

include "Conexao.class.php";

$dados = $_POST;

if($dados['acao'] == 'inserir')
{
    $conn = new Conexao();
    $conn->conectaBase();

    $cpf = $dados['cpf'];
    $nome = $dados['nome'];

    $sql = mysqli_query($conn->link,"SELECT * FROM acolhidos WHERE cpf = '$cpf' ");

    $existecpf = mysqli_num_rows($sql);

    // Se o número do CPF já existe na tabela ACOLHIDOS, retornar mensagem de erro.

    if ($existecpf != 0){
        //redireciona a página para o html passando os dados por get
        header("location: ./caminho/do_formulario.html?cpf=$cpf&nome=$nome&mensagem=CPF%20já%20existe");
        exit;
    }

    $sql = "INSERT INTO acolhidos
    (
    nome,
    cpf
    )
    VALUES
    (
    '$dados[nome]',
    '$dados[cpf]',
    )";
    $query = mysqli_query($conn->link, $sql);
    echo mysqli_error($conn->link);
}

$conn->desconecta();

And in HTML just show the data:

<form class="form" name="frmCadAcolhido" method="post" action="insert.php">
<input type="hidden" name="acao" value="inserir" >

    <label class="control-label">Nome</label>
    <input type="text" class="control" name="nome" value="<?php echo $GET["nome"]; ?>" required>

    <label class="control-label">CPF</label>
    <input type="text" class="control" name="cpf" value="<?php echo $GET["cpf"]; ?>" required maxlength="11">

    <input type="submit" name="btnCadastar" value="Cadastrar">
</form>
<p>
    <?php echo $GET["mensagem"]; ?>
</p>
    
29.03.2018 / 00:34
-1

You are sending a form request to the insert.php file, however the page that has the form is HTML and when sending the information the page is updated and in this case it is like a new page, ie the fields unfilled. You'd better use other means to do what you want.

If you want you can use JQuery as the example I left below:

<form class="form" id="frmCadAcolhido" name="frmCadAcolhido" method="post">
    <input type="hidden" id="acao" name="acao" value="inserir" />
    <label class="control-label">Nome</label>
    <input type="text" class="control" id="nome" name="nome" required />
    <label class="control-label">CPF</label>
    <input type="text" class="control" id="cpf" name="cpf" required maxlength="11" />
    <input type="button" id="btnCadastrar" name="btnCadastrar" value="Cadastrar" />
    <input type="reset" id="btnLimpar" name="btnLimpar" value="Limpar" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>$(function(){$('#frmCadAcolhido#btnCadastrar').on('click',enviaForm);});functionenviaForm(){varacao=$('#frmCadAcolhido#acao'),nome=$('#frmCadAcolhido#nome'),cpf=$('#frmCadAcolhido#cpf'),btn=$('#frmCadAcolhido#btnCadastrar');btn.prop({'disabled':true});//ajudaaevitarduploclickeváriasrequisiçõesif(acao.val()=='inserir'){if(nome.val()==undefined||nome.val()==null||nome.val()==''){alert('Favorpreencherocampo');nome.focus();btn.prop({'disabled':false});returnfalse;}elseif(cpf.val()==undefined||cpf.val()==null||cpf.val()==''){alert('Favorpreencherocampo');cpf.focus();btn.prop({'disabled':false});returnfalse;}else{$.post('insert.php',{acao:"\'" + acao.val() + "\'",nome: "\'" + nome.val() + "\'",cpf: "\'" + cpf.val() + "\'"},
                function(data){
                    alert(data); //Trate o resultado como quiser
                    btn.prop({'disabled':false});
                    return false; // impede a atualização da página e mantém as informações nos campos
                }
            );
        }   
    }else{ alert('Erro ao enviar form');btn.prop({'disabled':false});return false;}
}
</script>

I changed the input "submit" to "button" and added "id" to all input's.

    
29.03.2018 / 00:51