如何允许用户在页面上提交同一表单的多个实例并使用 php 存储数据


How do I allow a user to submit multiple instances of the same form on a page and store the data using php?

我正在开发一个由html表单组成的php项目,该表单允许用户提交文本,歌曲名称,作曲家和艺术家。用户填写表单并单击"提交"后,应存储数据并允许再次填写表单,直到用户按下另一个按钮,该按钮显示已提交的所有数据。到目前为止,我已经考虑使用数组,但我不确定这将如何与发送到同一数组的多个表单提交一起工作。任何帮助将不胜感激。

    <html>
      <head>
      </head>
      <body>
        <form method="post">
          Name of song: <input type="text" name="songName"><br>
          Composer: <input type="text" name="composer"><br>
          Artist/Group: <input type="text" name="artist"><br>
          <input type="submit" name="submit">
        </form>
      </body>

      <?php
        if (!empty($_POST['submit'])) {
          //Submit the data into the array or something here
        }
      ?>
    </html>

当然,试试这个,看看会发生什么:

<?php
    session_start();
    // Initialize an array for answers
    if (!isset($_SESSION['answers']))
        $_SESSION['answers'] = array();
?>
<html>
  <head>
  </head>
  <body>
    <form method="post">
      Name of song: <input type="text" name="songName"><br>
      Composer: <input type="text" name="composer"><br>
      Artist/Group: <input type="text" name="artist"><br>
      <input type="submit" name="submit">
    </form>
  </body>

  <?php
    if (!empty($_POST['submit'])) {
        // Push the posted data into the session array
        $_SESSION['answers'][] = $_POST;
    }
    // Display the data now
    foreach($_SESSION['answers'] as $array) {
        echo "Name of song: {$array['songName']}<br>";
        echo "Composer: {$array['compose']}<br>";
        echo "Artist/Group: {$array['artist']}<br><hr>";
    }
  ?>
</html>

注意:会话仅保留到用户注销或超时。为了长时间持久化,您需要使用 MySQL 等数据库来存储答案