1

I'm trying to ask a user how many guests. Once the user has entered a number then a number of fields should appear where the user can then add guest1, guest2 etc. However every time I try and create a for loop it doesn't seem to be working. This is the current source code for entering the number of guests.

<? echo "<input type='text' name='guestnumber' size='6' value='$guestnumber'>" ?>

What I would like to happen is that the name of the textfields would be guest1, guest2 etc based on the number of guests they have entered. I'm sure it's a pretty simple for loop that needs to be done but I'm not sure how to do it.

4

1 回答 1

2

这是一个基本的例子。提交表单不会重置字段。

您可以将所有值存储在单独的变量中,例如$guest1,等,但是在处理数据$guest2时使用数组要容易得多。$_POST

在接触任何变量之前,我们检查变量是否设置isset为防止错误。

<?php

// Set up the number of guests
if(isset($_POST['guestnumber'])) {
    $numGuests = (int)$_POST['guestnumber'];
    if ($numGuests < 1) {
        $numGuests = 1;
    }
}

if (isset($_POST['guests'])) {
    // Handle guest data
}

?>

<form method="POST" action="">
    <input type="text" name="guestnumber" size="6" value="<?php

        // Retain field value between refreshes
        if(isset($numGuests)) echo $numGuests; ?>"><br>

    <?php

    // Echo out required number of fields
    if (isset($numGuests)) {
        for ($i = 0; $i < $numGuests; $i++) {

            // Store field information in a 'guests' array
            echo "<input type='text' name='guests[]' value='";

            // Retain the guest names between refreshes
            if (isset($_POST['guests'])) {
                echo $_POST['guests'][$i];
            }

            echo "'><br>";
        }
    }

    ?>
    <input type="submit" value="Submit">
</form>
于 2013-04-28T01:23:10.470 回答