简体   繁体   中英

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

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 class="btn-secondary" 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;
    }
    }

?>

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 class="btn-secondary" 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;
    }
 }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM