0

We want to dynamically create a form with content from a database using arrays. Extracting the data from the DB is easy:

$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];
}

But how do we apply this data to the form so that the $id and $text correspond ?:

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

Many thanks in advance for any help!

Richard Tinkler
  • 1,635
  • 3
  • 21
  • 41

3 Answers3

1

Simply use one array for both.

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

And in your view

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

Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer in SO for more information.

Community
  • 1
  • 1
kero
  • 10,647
  • 5
  • 41
  • 51
1

Or try an associative array:

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

and then in the form:

foreach ($data as $id => $text) {
    // your code
}
kero
  • 10,647
  • 5
  • 41
  • 51
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

You can use the following:

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

Having said that, using a multi-dimensional array, as in kingkero's example, is the best way.

Styphon
  • 10,304
  • 9
  • 52
  • 86