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.

2
  • 2
    Give all code you've written. Commented Apr 28, 2013 at 1:02
  • use php's form-array support: name="guestnumber[]". add as many copies of the field as you'd like, you'll just end up with an array of values from all those fields in $_POST['guestnumber'] Commented Apr 28, 2013 at 1:03

1 Answer 1

2

Here is a basic example. Submitting the form does not reset the fields.

You can either store all values in separate variables such as $guest1, $guest2, etc, but an array is much easier to use when handling the $_POST data.

Before touching any of the variables we check if the variable is set with isset to prevent errors.

<?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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.