I have this php code:
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button'.$i.'"><b>Answer</b></button>';
echo '</form>';
}
Now I want to get the question number for which the answer_button
is clicked.
Closest I could get was this:
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button"><b>Answer</b></button>';
echo '</form>';
if(isset($_POST['answer_button'])) {
echo $i;
break;
}
}
This gives me Question number but it will not print other questions in loop once the button is clicked.
Is there no solution without using javaScript?
Change the html markup to use an "array notation":
echo '<button name="answer_button['.$i.']" type="submit">Answer</button>';
That will cause php to populate an array when receiving back the form which you can examine:
<?php
// ...
if(isset($_POST['answer_button']) && is_array($_POST['answer_button'])) {
$id = array_shift(array_keys($_POST['answer_button']));
// ...
}
This allows to have multiple such buttons in a single form and detect which one has actually been clicked. It works, because $_POST will contain an array with a single element with key as in $id
, which you can easily examine yourself with a var_dump($_POST);
or similar.
This should work :
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button'.$i.'"><b>Answer</b></button>';
echo '</form>';
echo '</div>';
}
for($i=0;$i<3;$i++) {
if(isset($_POST["answer_button".$i])) {
echo $i;
}
}
Hope it helps.
I think this is what your looking for.
CODE
<?php
echo '<form action="" method="POST">';
for ($i = 0; $i < 3; $i++) {
echo 'Question: ' . $i . '<br>';
echo 'Answer..<br>';
echo "<textarea name='answer[$i]'> </textarea></br>";
echo "</br><button name='answer_button[$i]' value='BtnPushed'> <b>Answer</b></button><br>";
if (! empty($_POST['answer_button'][$i])) echo "Last Answer: {$_POST['answer'][$i]}<br>";
echo '<hr>';
}
echo '</form>';