Pass variable with various input/select

Asked

Viewed 1,143 times

2

I have a form with several input that I create with a for cycle, I pass by POST to another page and change its name as in the example:

<form action="page2.php" method="post">
<?php 
    for($i=1; $i<=10; $i++){ 
?>
<select name=fichier<?php echo $i?> > (...)

The problem is if I don’t want to fill in the input or select, how do I receive its value? Not to repeat code for the various inpuut I have it on the other page that receives the POST.

for($i=1; $i<=10; $i++){
    if (isset($_POST['fichier'.$i])) 
    {
        $fichier = htmlentities($_POST['fichier'.$i]);
    }

    if(isset($_POST['fichier'.$i])== 0){
        break;
    }
    //echo $fichier;
}

2 answers

2

You can name inputs with brackets at the end, Ex:

<?php

if (isset($_POST)) {
    var_dump($_POST);
}

?>

<form method="post">
    <input id="itens[]" name="itens[]" value="text1" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text2" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text3" type="text" /><br>
    <input id="itens[]" name="itens[]" value="text4" type="text" /><br>
    <input type="submit" />
</form>

Exit:

array (size=1)
  'itens' => 
    array (size=4)
      0 => string 'text1' (length=5)
      1 => string 'text2' (length=5)
      2 => string 'text3' (length=5)
      3 => string 'text4' (length=5)

0

How do you have a form with several input, and do not want to repeat the values the solution would be to insert a name with [] at the end for the values to be saved in an array.

Example:

page.html

<form action="page2.php" method="post">
   Input1 <input id="fichier[]" name="fichier[]" type="text" /><br>
   Input2 <input id="fichier[]" name="fichier[]" type="text" /><br>
   Input3 <input id="fichier[]" name="fichier[]" type="text" /><br>
    <input type="submit" value="Enviar" />
</form>

page2.php

<?php 
    if (isset($_POST['fichier'])) {
        var_dump($_POST['fichier']);
    }   
 ?>

Exit after POST:

array(3) { [0]=> string(6) "texto1" [1]=> string(6) "texto2" [2]=> string(6) "texto3" }

Browser other questions tagged

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