-1

I want to post some inputs which are included in a loop. The problem is that when I click the sumbit button only the last value of the input is posted. Any suggestions?

while ($i <= $number) {
    echo '<label class="col-6 col-lg-4 col-form-label">Question ' . $i . '</label><br>
    <input class="col-6 col-lg-6  form-control" name="question" id="question" placeholder="Type your question" required/><br>
    <div class="form-group row">
        <label class="col-6 col-lg-4 col-form-label">Answer 1</label>
        <div class="col-6 col-lg-8 d-flex align-items-center">
            <input name="correct_answer"  type="text" placeholder="Correct answer goes here" required/>
        </div>
    </div>
    <div class="form-group row">
        <label class="col-6 col-lg-4 col-form-label">Answer 2</label>
        <div class="col-6 col-lg-8 d-flex align-items-center">
            <input name="wrong_answer" type="text" placeholder="Type a wrong answer" required/>
        </div>
    </div>
    <div class="form-group row">
        <label class="col-6 col-lg-4 col-form-label">Answer 3</label>
        <div class="col-6 col-lg-8 d-flex align-items-center">
            <input name="wrong_answer2" type="text" placeholder="Type a wrong answer" required/>
        </div>
    </div><hr>';

    $i++;

    if(isset($_POST['question'])) {
        $question = $_POST['question'];
        echo $question;
    }

}
Mark
  • 1,852
  • 3
  • 18
  • 31
giannis
  • 9
  • 2

2 Answers2

0

This is normal because you erase the name of each input ,and you will send only the last inputs un your loop to avoid this you can add [] as a suffix of each name in yours inputs or selects ... example:

 <input name="wrong_answer2[]" type="text" placeholder="Type a wrong answer" required/>

and for recuperate it, you must read it as a array, like this, i supose you use the method post in your form:

$wrong_answer2 = (array) $_POST['wrong_answer2'];

Have Fun :)

0

The inputs have the same name. This means that if they are in the same form, the last one will overwrite the others. As a solution you could for example use the $i variable to make all the names unique.

Another solution could be to use arrays. POST an array from an HTML form without javascript describes the array solution.

Teun
  • 916
  • 5
  • 13