设置不同的选项并获取它们的值


Setting up different options and getting their values

我正在使用以下代码将各种select元素添加到我的页面中。然而,当我在while循环中这样做时,所有元素的值都是相同的

function options($pos, $count) {
    for ($i = 0; $i < $count; $i++) {
        $options = '';
        $STH = //code to get data from db
        $STH->execute();
        while($row2 = $STH->fetch()) {
            $options .="<option>" . $row2['name'] . "</option>";
        }
        $menu= "<select name='filter' id='filter'>
            " . $options . "
            </select>";
        echo $menu;
    }
}

然后,我需要在用户按下按钮后获得每个select元素的值。但由于每个select元素的名称都是相同的,我不知道如何做到这一点。有什么办法解决这个问题吗?

例如,如果计数为5,将创建五个单独的下拉列表(即使每个列表中的选项相同)。然后,用户选择与其相关的选项并按下提交按钮。然后我需要获得他从下拉菜单中选择的值,但我不知道如何做到这一点,因为所有下拉菜单的名称都是相同的

假设您有许多带有动态选项的select标签

解决方案是使您的选择标签的名称不同(动态)

<form method="POST">
<?php
cust_options(5);
function cust_options($count) {
    for ($i = 0; $i < $count; $i++) {
        $options = '';
        $j = 1;
        while($j < 4) {
            $options .="<option>" . 'option'.$j . "</option>";
            $j++;
        }
        $ind = $i+1;
        $temp = 'filter_'.$ind;
        $menu= "<select name='$temp'>
            " . $options . "
            </select>";
        echo $menu;
    }
}
?>
<input type="submit">
<?php print_r($_POST); ?>
</form>

您应该这样做:

<select name='filter' id='filter'>
  <?php 
     while($row2 = $STH->fetch()) {
            $options .="<option>" . $row2['name'] . "</option>";
     } ?>
</select>";