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条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致