Check empty fields with foreach

Asked

Viewed 512 times

1

I have a form system where the fields are generated by the base date through select. The same is done with foreach, how can I search the base date for the required fields and see if they have been filled in? And if they are not going to validate the form and show a message. NOTE: I don’t want to use required 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" />
  • Can be done only with javascript can be?

  • Hi Felipe! So I didn’t want to javascript. I saw on a site the same system and it was made by php even, at the time of entering the base date checked the mandatory fields of the form if they were filled, otherwise it showed the message You left the field [FIELD NAME] blank that was required.

  • Well, then it can be done on the server but it will not be in real time, every time the user submits the form, it will go to another validation page, when returning the completed data will be lost.

  • Even so, I prefer the server!

  • Okay, I’ll get back to you.

  • And how should it be done to know which field is mandatory? By column obrigatorio? And even if you do such a check on the server, which should be done, I strongly recommend using the required in HTML. This will prevent the user from making multiple unnecessary requests to the server.

  • Yes required column (yes or no). I used required, but I still prefer to use it by php!

  • @Carlosg this PHP code right at the beginning is what the request is about and should do such validation?

  • @Andersoncarloswoss Yes, I thought about selecting the required fields of the form with select before foreach and using something like if(Empty($result)){ does it give?

  • @Carlosg Many errors occur in your logic. You can’t just do what you want, because there are good practices in programming and usability. Validating forms through the server, after refreshing, is far from being a coherent solution, because the javascript usage does not present any kind of risk to your application and does not hinder what Voce is trying to do. If there is a reason for you to take it away, speak soon, but for now I can answer that you give up what you want to do, for usability reasons.

  • 1

    @Carlosg does not need to edit the answer, saying it solved the problem. Leave the question as it is, with the answer already given, to help other people.

Show 6 more comments

2 answers

0

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

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

php form.

<?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 haven’t tested it, but it’s likely to work.

I will explain why the second alternative is unfeasible.

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

  • You will lose the form data.
  • It will lose in maintainability because it will be stuck to a rule.
  • Lose in server requests and in performance.
  • And what a racket this would be?

  • 2

    It would be too much to ask why it would be gambiarra to use the column obrigatorio of the database?

  • I added the necessary information.

  • 1

    Doesn’t static validation get more tied to a rule? You need to manually define the names of the fields and, since they are dynamic, there is no way to know which ones are.

  • By no means @Andersoncarloswoss, static validation is not an example of dynamization, but judging that an application has more than one form, the maintenance of these mandatory fields in the bank would be horrible, by the way, this term dynamization did not go well, I will change.

0


It is very important, both in terms of usability and performance that you at least place the property required 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 in, and will also prevent your server from having to validate several unnecessary requests. It is also worth noting that even doing this on the client side, server validation is required. Never trust your customer’s data.

So, I stuck to the code regarding the validation of the form. If I understand correctly, the submission of the form will generate values of the type:

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

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

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 that, you could display the error messages in the form by doing:

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

Important reading: Why should we not use mysql type functions_*?

  • I gave an adapted and it worked perfectly. Thank you

Browser other questions tagged

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