Forum Moderators: coopster

Message Too Old, No Replies

Generating multiple fields through a Loop

         

HoboTraveler

7:16 pm on Mar 23, 2006 (gmt 0)

10+ Year Member



Hi All,

Is it possible to create a form where the fields are generated through a loop?

Example: My database has 20 columns

I create a PHP form and use a loop to define the number of rows. The loop generates a table of 20 columns and 50 rows.

After entering the data into these fields, I click add and another loop enters all of the data into the DB.

I do know that this is possible by defining each variable in each field. But, it would take quite some time to define 50 or 100 fields.

So a loop looks to be the easiest way in generating the 20 columns and 50 rows.

Any ideas?

Thanks

coopster

7:43 pm on Mar 23, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, HoboTraveler.

I don't see why you couldn't. Where are you stuck?

HoboTraveler

6:12 am on Mar 24, 2006 (gmt 0)

10+ Year Member



Hello,

I need a snippet of code that will generate the columns and rows and how the loop will declare the variables..?

Thanks.

omoutop

8:29 am on Mar 24, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



// db connect
// execute simple SELECT * FROM table
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
$i=0;
foreach ($line as $col_value)
{
$field=mysql_field_name($result,$i);
$array[] = $field;
$i++;
}
}

so now you have an array with all field names in your db table
for our example let just say that your table id is first in the table, at $array[0]
and that you dont want it in your form fields (so 19 columns, $array[1] through $array[20]
//$i = columns (19)
//$j = rows (50)

<table>
<? for ($j=1;$j<=50;$j++) {?>
<tr>
<? for ($i=1;$i<=20;$i++) {?>
<td><input name="<? echo $array[$i]."_".$j;?>" type="text"></td>
<? }?>
</tr>
<? }?>
</table>

the above code will give you all the fields you need as : table_column_name_x (name_1, lastname_1, address_1, name_2, lastname_2, address_2, etc)
reversing the above you will have your $_POST fields to insert/update your db

so create new array with table names from db, $array2 for example

for ($k=1;$k<=50;$k++)
{
for ($m=1;$m<=20;$m++)
{
$my_field = $array2[$m];
$my_field_value_temp = $my_field."_".$k;
$my_field_value = $$my_field_value_temp;
//update-insert your table with ".$my_filed."='".$my_field_value."'
}
}

Hope you got the idea. Good luck and **NOTE** i havent tested the above code - its just theory. The loop which creates the array with field names is from php.net manual :)
?>