从数据库填充PHP数组以创建动态HTML表单

时间:2013-11-15 16:33:27

标签: php mysql arrays

我们希望使用数组动态创建包含数据库内容的表单。从数据库中提取数据很简单:

$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和$ text对应?:

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

非常感谢您的任何帮助!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

或尝试关联数组:

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

然后以表格形式:

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

答案 2 :(得分: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的例子中,是最好的方法。