2013-11-15 43 views
0

我們希望使用數組動態創建包含數據庫內容的表單。提取數據庫中的數據很容易:從數據庫填充PHP數組以創建動態HTML表單

$sql_inhalt = "SELECT * FROM tbl_inhalt ORDER BY id ASC"; 
$result_inhalt = mysql_query($sql_inhalt) or die("INHALT".mysql_error()); 
while($rs_inhalt = mysql_fetch_row($result_inhalt)){ 
     $id[] = $rs_inhalt[0]; 
     $text[] = $rs_inhalt[2]; 
} 

但是我們怎麼這個數據適用於表單,以便$ ID和$文本對應:

<form id="form1" name="form1" method="post" action="..." > 
<?php foreach($text as $out_text){ 
    echo '<textarea name="'.$id.'" type="text" class="mceEditor" cols="85" rows="5" />'.$out_text.'</textarea>'; 
}?> 
</form> 

提前許多感謝任何幫幫我!

回答

1

只需使用一個數組即可。

while ($rs_inhalt=...) { 
    $data[] = array($rs_inhalt[0], $rs_inhalt[2]); 
} 

而且在你看來

foreach ($data as $pair) { 
    // acces id as $pair[0] and text as $pair[1] 
} 

而且記住,mysql_*功能officially deprecated,因此不應在新代碼中使用。您可以改用PDO或MySQLi。有關更多信息,請參閱this answer in SO

0

您可以使用以下方法:

<form id="form1" name="form1" method="post" action="..." > 
    <?php foreach($text as $i => $out_text){ 
     echo '<textarea name="'.$id[$i].'" type="text" class="mceEditor" cols="85" rows="5" />'.$out_text.'</textarea>'; 
    }?> 
    </form> 

話雖如此,使用多維數組,如kingkero的例子,是最好的辦法。

1

或者嘗試關聯數組:

while ($rs_inhalt=...) { 
    $data[$rs_inhalt[0]] = $rs_inhalt[2]; 
} 

然後在形式:

foreach ($data as $id => $text) { 
    // your code 
}