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.