How not to lose the form fields, after validation with PHP

Asked

Viewed 2,005 times

0

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

Although my production form has a lot of fields, I am using the code below with only 2 fields to simplify: inserir a descrição da imagem aqui

<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" 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 on the button, the script in "Insert.php" is submitted. First, it checks whether the CPF entered by the user already exists in the table through a query to the Mysql database. If the CPF does not exist, an INSERT of the fields is made in the table. But if the CPF already exists, it displays an error message and returns to the form. Follow 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 could I do so that when returning to the form, the data entered by the user remain filled?

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

  • Utilize flash Session

  • @Valdeirpsr, do you refer to PHP Flash Messages? as in https://mikeeverhart.net/php-flash-messages/

  • It may be, but you can implement it. Just save the POST in a Session in the insert.php and after using them in HTML, just destroy them.

2 answers

1


In PHP, if you already have CPF, direct redirect by php passing the data by 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 only 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>
  • the problem is that my complete form has more than 50 fields... in this case, it is impossible to send everything by GET?

  • I believe then that you should decrease these fields, for example, I have a project in which the user type only name and phone and do a search, if there is no one, he can add the other fields, put on the first screen only the essential fields after it fills the others.

  • But if you need the 50 fields, one option would be to create a session with these values, redirect to the form, display the data (saved in the session), and destroy it, another option is, as said in the other answer, to make asynchronous requests with AJAX

  • I like your suggestion! I will make a 'pre-form' only with the fields name, datanasc and Cpf, and after validating that the registration really does not exist in the bd, I will open a form with the other fields.

  • This also increases the user’s experience, imagine filling 50 fields and in the end do nothing, it would be very frustrating

-1

You are sending a request via form to the file Insert.php, but 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 form fields will be unfilled. It would be better if you used other means to do what you want.

If you want you can use Jquery according to 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);
    });
    function enviaForm(){
    var acao = $('#frmCadAcolhido #acao'),
    nome = $('#frmCadAcolhido #nome'),
    cpf = $('#frmCadAcolhido #cpf'),
    btn = $('#frmCadAcolhido #btnCadastrar');
    btn.prop({'disabled':true}); // ajuda a evitar duplo click e várias requisições
    if(acao.val()=='inserir'){
        if(nome.val()==undefined || nome.val()==null || nome.val()==''){
            alert('Favor preencher o campo');
            nome.focus();
            btn.prop({'disabled':false});
            return false;
        }
        else if(cpf.val()==undefined || cpf.val()==null || cpf.val()==''){
            alert('Favor preencher o campo');
            cpf.focus();
            btn.prop({'disabled':false});
            return false;
        }
        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 switched the input "Submit" to "button" and added "id" to all input’s.

  • before signaling negative, post your answer as help, only negative does not help, at least put your justification to negative.

  • Never start an answer by saying 'use jQuery'. By the way, it was not I who negatived, the solution may be valid but it should be library independent.

  • @epx changed the term "use jQuery", but you can post a library-independent solution?

  • @Wilsonrosagomes, this solution will also work if we’re working with 50 or more fields in the form?

  • Yes, and you can validate the fields, I will improve the example and put a validation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.