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:
<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
– Valdeir Psr
@Valdeirpsr, do you refer to PHP Flash Messages? as in https://mikeeverhart.net/php-flash-messages/
– Romulo Rocha
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.– Valdeir Psr