views:

52

answers:

1

Hi guys! I have a question regarding the creation of Auto Dynamic text boxes within PHP. The scenario is like this:

  • I have 2 tables in a MySWL database.
  • The 2 tables (students/teachers) have different number of fields
  • Teachers = 8 fields / Students = 5 fields
  • A page for inserting new data into the tables is created.

So now there is a need to allow the "insert" page to auto generate the number of fields found within the table to allow inserting of data instead of creating 2 different PHP pages for the website.

I think that by including array into <input type="text" name="TableFieldArray[]" size="40" maxlength="256"> can be used to auto generate the number of fields needed for the insertion of the new data.

Please kindly give some suggestions. Thanks!

A: 

adapted from example #1 on this page in the php manual:

<?php
$result = mysql_query("SHOW COLUMNS FROM Teachers");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        echo "<label for=\"ff-{$row['Field']}\" >{$row['Field']}</label>";
        echo "<input id=\"ff-{$row['Field']}\" type=\"text\" name=\"{$row['Field']}\" size=\"40\" maxlength=\"256\" />";
    }
}

That will give you one <input> element for each column in the Teachers table. The input elements will be named the same as their corresponding mysql columns.

Lee
Is there a way to show the name of the fields also? Thanks.
JavaNoob
Sure. Just add a `<label>` to go with the input field. The label's text content and the `for` attribute would get pulled from the information in `$row` -- same as the `name` attribute on the `<input>` field. I updated the example to demonstrate.
Lee