Home > database >  php - how to send all selected option values of 3 select boxes with for loop?
php - how to send all selected option values of 3 select boxes with for loop?

Time:11-30

i am trying to create 3 select boxes using for loop and send all selected option values of each box, but the result only loop the first selected value of 3 boxes. here is the code:

<?php
for ($a=0; $a < 3; $a  ) {
?>
    <form action="" method="POST" id="formid">

        <select  name="selectid">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
    </form>
<?php  }?>
<input type="submit" name="submit" form="formid" value="Submit">


<?php
if (isset($_POST['submit'])) {
    $selectid = $_POST['selectid'];
    for ($i=0; $i < 3 ; $i  ) {
        echo $selectid;
    }
    }

?>

CodePudding user response:

First of all, you need to put all the elements into a single shape. In your case, you create a new shape for each loop pass.

If you add [] to the name of your selects, then everything will be put into an array. Instead of name="selectid"u should do something like name="selectid[]"

Should be something like that, if u check $_POST

[selectid] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
    )

So your entire Loop should looks like that :

<form action="" method="POST" id="formid">
<?php
for ($a=0; $a < 3; $a  ) {
 ?>
    <select  name="selectid[]">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    <?php  }?>
    <input type="submit" name="submit" form="formid" value="Submit">
</form>
<?php

if (isset($_POST['submit'])) {
   $selectid = $_POST['selectid'];
   // Here you can access every Select 
   // [0] -> 1st select , [1]-> 2nd select....
   foreach($selectid as $id){
       echo $id;
    }
 }
?>
  • Related