Richard Tinkler
Richard Tinkler

Reputation: 1643

Populating PHP arrays from a DB to create a dynamic HTML form

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!

Upvotes: 0

Views: 340

Answers (3)

kero
kero

Reputation: 10638

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.

Upvotes: 1

Carsten Massmann
Carsten Massmann

Reputation: 28196

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
}

Upvotes: 1

Styphon
Styphon

Reputation: 10447

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.

Upvotes: 0

Related Questions