Check empty fields with foreach

1

I have a form system where fields are generated by the base date through select. The same is done with foreach, how can I fetch the base date from the required fields and see if they were filled in? And if they are not do not validate the form and display a message. OBS: I do not want to use required no input.

<?php
if (isset($_POST['acao'])) {
    while (list ($key, $val) = each ($_POST)){ 
    mysql_query("insert into cms_formularios_respostas(usuario,resposta,campo,formulario) values('$name','".strip_tags($val)."','$key','$row[id]')") or die(mysql_error()); 
    }
}
?>
<form method="post" enctype="multipart/form-data" style="margin-bottom:5px"> 
<input type="hidden" name="acao" id="acao" value="<?php echo $row['id']; ?>" /> 
<?php
$get_form = mysql_query("SELECT * FROM cms_formularios_campos WHERE formulario = '$row[id]' ORDER BY ID") or die(mysql_error());
while($form = mysql_fetch_assoc($get_form)){
?><p><label class="label-form" for="<?php echo $form['id']; ?>"><?php echo $form['nome']; ?></label><br /><?php if($form['tipo'] == 'Resposta curta'){ ?><inputtype="text" name="<?php echo $form['id']; ?>" id="<?php echo $form['id']; ?>" class="input-form" /><br><?php if($form['obrigatorio'] == 'sim'){ ?><span style="color:red">* Requerido</span><?php } ?><?php } ?></p><input type="submit" class="input-form" value="Enviar" />
    
asked by anonymous 08.11.2017 / 12:20

2 answers

0

It's very important, in terms of both usability and performance, that you at least put the required property in your HTML in the required fields. This will cause the user to be informed in real time, with a message in the browser, about which fields he should fill and also prevent his server from having to validate several unnecessary requests. It is also worth noting that even doing this on the client side, validation on the server is mandatory. Never trust your customer's data .

So, I'll stick to the form validation code. If I understand correctly, submitting the form will generate values of the type:

$_POST = [
    "acao" => "1",  // $row['id']
    "1" => ...,
    "2" => ...,
    "3" => ...,
];

Where the acao field is defined by the value of $row['id'] and the others refer to the fields registered in the database. To find out which ones are required, you'll need to re-search the values in the database:

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    $formulario = filter_input(INPUT_POST, 'acao', FILTER_VALIDATE_INT);
    $query = mysql_query("SELECT id, nome FROM cms_formularios_campos WHERE formulario = '{$formulario}' and obrigatorio = 'sim' ORDER BY ID") or die(mysql_error());

    $erros = [];

    while($campo = mysql_fetch_assoc($query))
    {
        if (empty($_POST{$campo["id"]}))
        {
            // Algum campo obrigatório está em branco. Definir lógica do erro.
            $erros[] = "O campo {$campo['nome']} é obrigatório e não foi preenchido.";
        }
    }

    if (count($erros) === 0)
    {
        // Insere os valores da tabela de respostas
        // Utilize o input_filter ou filter_input_array para tratar os dados
    }
}

After this, you would be able to view the error messages on the form by doing:

foreach($erros as $erro)
{
    echo "<div class='erro'>{$erro}</div>";
}

Important reading: Why should not we use functions of type mysql_ *?

    
08.11.2017 / 13:43
0

Starting from the logic, you are creating a form dynamically, with data coming from the bank, legal, but the field 'obligatory' in the forms column, will not serve anything, when submitting the form to the server, we can get the global variable generated by its name , and its value, we can not identify whether the input was mandatory or not.

So you have 2 alternatives, do a static validation, or a gambiarra to be able to use the 'obligatory' field of the bank, I will demonstrate the first alternative.

form.php

<?php if(isset($_GET['empty'])){ ?>
  <strong id="empty">Erro! Favor preencher todos os campos!</strong>
<?php } ?>


<form action="valida.php" method="POST">

<input type="text" name="value1">

<input type="text" name="value2">

<input type="text" name="value3">

<input type="submit" value="enviar">

</form>

valida.php

<?php

//Caso value1 e value3 sejam obrigatórios.

if(empty($_POST['value1']) || empty($_POST['value3'])) {
     header( 'location: formulario.php?empty#empty' ); exit();
}

...

?>

I did not test but it is likely to work.

  

I will explain why the second alternative is impractical.

As I said before, not validating on the client, will bring numerous disadvantages, because when submitting, you would have to search the required fields in the database, bringing some identifier attribute to the same, eg an id (I believe you have this field because your code will appear), this id would have to be in accordance with the form name, so it will be checked, with a looping for each value, so you ...

  • You will lose the form data.
  • You will lose in maintainability because you will be bound by a rule.
  • You will lose in server requests and performance.
08.11.2017 / 13:00