for循环中的多重选择在返回表单时丢失了它的数据


Multiple select in an for loop is losing it's data when returning to the form

我有一个表单,在while循环中有一个多重选择:

while ($row_i = mysql_fetch_array($res_i))
{
    $i++;
    // maak select name
    $name_bewerking_id = 'bewerking_id'.$i;
    ?>
    <tr valign="top">
        <td>
        <select name="<?php echo $name_bewerking_id ?>[]" multiple="multiple" size="2">
        <?php
            $sql = "SELECT id, bewerking FROM bewerkingen ORDER BY bewerking ASC";
            $res = mysql_query($sql,$con);
            while ($row = mysql_fetch_assoc($res))
            { ?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['bewerking']; ?></option>
        <?php } ?>
        </select>
        </td>
    </tr>
<?php
}

发送表单时:

$bewerking_id[$i] = array();
$bewerking_id[$i] = $_POST['name_bewerking_id'][$i];
if(isset($bewerking_id_temp[$i]))
{
    foreach($bewerking_id_temp[$i] as $temp[$i])
    {
        array_push($bewerking_id[$i], $temp[$i]);
    }
}

返回到形式:

for ($i = 0; $i <= $aantal_regels_corr; $i++)
{
    // maak select name
    $name_bewerking_id = 'bewerking_id'.$i;
    ?>
    <tr valign="top">
        <td>
        <select name="<?php echo $name_bewerking_id ?>[]" multiple="multiple" size="2">
        <?php
            $sql = "SELECT id, bewerking FROM bewerkingen ORDER BY bewerking ASC";
            $res = mysql_query($sql,$con);
            while ($row = mysql_fetch_assoc($res))
            { ?>
                <option <?php if(isset($bewerking_id[$i]) && in_array($row['id'], $bewerking_id[$i])){ echo 'selected="selected"'; } ?> value="<?php echo $row['id']; ?>"><?php echo $row['bewerking']; ?></option>
        <?php } ?>
        </select>
        </td>
    </tr>
<?php
}

当返回到表单时(当其中一个字段没有被填写时),所选择的选项将丢失并且不再被选择。

我哪里搞砸了?

您读取具有此标识符的POST数据'name_bewerking_id'

,但选择名称是由<?php echo $name_bewerking_id ?>$name_bewerking_id = 'bewerking_id'.$i

如果假设您在3个不同的页面之间传递表单信息,则需要为此使用$_SESSION变量。普通的PHP变量不能在页面之间传递,只有$_SESSION变量可以。

例如:

第1页

<form ...>
    <input name="text1" type="text" />
    <input type="submit" />
</form>

第2页

// must start the session before session variables can be used
start_session();
$inputTextBox1 = $_SESSION["textBox1"] = $_POST["text1"];

第3页

<?php start_session(); ?>
<html>
    ...
    <form ...>
        <select>
            <?php while ... { ?>
                <option <?php if(!empty($_SESSION["textBox1"])) { echo "selected='"selected'""; } ?>>Some Text</option>
            <?php } // End while ?>
        </select>
    </form>
    ...
</html>