2012-09-23 21 views
3

我有以下HTML表單,它是從MySQL數據庫中的表中動態生成的。我該如何在HTML表單中創建這個數組結構?

<form method="post" name="chapters" action="ChaptersUpdate.php"> 
<input type='text' name='id' value='{$row['id']}'> 
<input type='text' name='name' value='{$row['name']}'> 
<input type='password' name='password' value={$row['password']};> 
<input type='submit'> 
</form> 

我正在尋找一種方法,使這類表單提交時,下面的數據結構被傳遞在$ _ POST:

[chapter] => Array 
    (
    [0] => Array 
     (
      [id] => corresponding chapter ID 
      [name] => corresponding chapter name 
      [password] => corresponding chapter password 
     ) 

    [1] => Array 
     (
      [id] => corresponding chapter ID 
      [name] => corresponding chapter name 
      [password] => corresponding chapter password 
     ) 

) 

我試過名稱的各種組合='章[] [id]'/ name ='chapter [] [name]'/ name ='chapter [] [password]',但收效甚微。數組數據結構看起來不像我想要的樣子。

任何想法?

回答

0

您可以簡單地創建表單像這樣

<form method="post" name="chapters"> 
<?php 
for($i = 0; $i <3; $i++) 
{ 
    echo "ID: <input type='text' name='chapters[$i][id]' /> <br />"; 
    echo "Name: <input type='text' name='chapters[$i][name]' /> <br />"; 
    echo "Password: <input type='text' name='chapters[$i][password]' /> <br /> "; 
    echo "<Br />"; 
} 
?> 
<input type='submit'> 
</form> 

示例PHP

if(isset($_POST['chapters'])) 
{ 
    echo "<pre>"; 
    print_r($_POST['chapters']); 
} 

樣本輸出

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [name] => Name1 
      [password] => Password1 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [name] => name 2 
      [password] => password 2 
     ) 

    [2] => Array 
     (
      [id] => 2 
      [name] => name 3 
      [password] => Password 
     ) 

) 
+0

對,所以我實際上在做類似的事情。實際創建這些輸入字段的PHP組件是:while($ row = mysql_fetch_array($ result)){echo「」; }其中$ result = mysql_query(「SELECT * FROM chapters」)。奇怪的是,當我檢查實際生成的HTML頁面的源代碼時,它不顯示「章節[1] [id]」......它只是顯示「章節[] [id]」。這可能是問題的一部分嗎? –

+0

看看我的代碼,你會看到'for($ i = 0; $ i <3; $ i ++)'......什麼時候創建它們...... – Baba

+0

ohhhh,所以在我的情況下,for循環會在我在開始時使用的while()循環? –

2

以下似乎爲我工作:

<input type='text' name='chapters[0][id]'> 
<input type='text' name='chapters[0][name]'> 
<input type='password' name='chapters[0][password]'> 

<input type='text' name='chapters[1][id]'> 
<input type='text' name='chapters[1][name]'> 
<input type='password' name='chapters[1][password]'>