Andy Andy - 9 months ago 45
HTML Question

Collecting inputs from user within foreach loop (Using HTML and pHp)

I want the user to be able to input details regarding each exercise that is listed. However the number of exercises that show up is not set (user could select a verying number of exercises so I cannot use a set number of input boxes). How do I make it so that for each time the for loop is ran, a new input box will show up (1 for each exercise)?

foreach($exer->results() as $ex){
echo $ex->Name."<br/>";
// for each exercise I want to collect an input from user

Answer Source

You can get the exercise count from the user. You loop that amount of iterations in a for loop. Inside the loop add text fields. make sure you use name like data[user][].

$user_ex_count = 5; // Lets say you get 5 from a text box
for ( $x = 0; $x < $user_ex_count; $x++ ){
    echo '<input type="text" name="data[user][]">';

Then when you submit, your $_POST will have $_POST['data'] (which is an array.

So you can do,

if ( isset($_POST['data']) ){
    foreach( $_POST['data'] as $key -> $userInput ){
        echo $userInput; // user input values

This is just a dummy code to let you understand the flow. So that you can work on.

Hope this helps!