2013-10-14 20 views
0

我正在開發一個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> 
+0

只需將底部的PHP代碼存儲到數據庫中。它會自動再次顯示錶單,除非您做某些事情來阻止它。 – Barmar

+0

我想你可以將結果存儲在會話中的數組中。或者如果他們需要像上面那樣堅持在數據庫中。 –

+0

@ francisco.preller你可能提供一個你的意思嗎?特別是在會議中。 – user2177896

回答

1

當然,試試這個,看看會發生什麼:

<?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> 

注:僅SESSIONS保留,直到用戶註銷或他們超時。對於長時間的持久性,您需要使用數據庫(如MySQL)來存儲答案

+0

工作完美,謝謝!不過,我還有一個額外的問題。 print_r ...以相當不吸引人的方式輸出數據。如何爲所有數據打印所有更像Song:songName,Composer:composer等的數據? – user2177896

+1

正如註釋所述,print_r()方法主要用於調試,要正確地打印出來,您必須使用foreach循環,然後使用'echo'輸出html。請參閱此處以獲取更多信息:http://php.net /manual/en/control-structures.foreach.php –

+0

我添加了這個:if(!empty($ _ POST ['display'])){foreach($ _SESSION ['answers'] as $ value){ echo $值; } }並且它只是簡單地輸出ArrayArray ...,無論多次提交表單。 – user2177896

相關問題