douzhi9635 2016-02-14 14:56
浏览 19
已采纳

找到在php循环中生成的变量

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?

  • 写回答

3条回答 默认 最新

  • douhuai4155 2016-02-14 15:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料