Dynamic form generation

Dynamic form generation

Sometimes you need to create the form which content depends on the user’s behavior or the dynamically changed data taken from the database. The main difficulty is that the content of the lists is unknown beforehand. I’ll show the method for evading it.

So, some database there is a table that looks like:

1    Alex    Moscow...    
2    Piter    St.Piter...    
3    Paul    Paris ...    
...    ...    ...

It means that it can be changed by users. Our task is to output table content to the list. So, let’s start:

<?php
...
// The connection to the database process we’ll omit
...
// Select the information from the table
$table mysql_query("SELECT * FROM table" or die("Can’t make the fetch from the table");
// Prepare the form
<form action="script.php">
<
select name="list">
// Generate the list by means of the while cycle
while ($res mysql_fetch_array($table))
{
// Form the list string
$out_string $res["number"]." ".$res["Name"]." ".$res["Address"];
// Output the formed string
echo"<option value=".$res[number].">".$out_string."";
}
</
select>
</
form>
?>
So, our list will look like:


Using that method you can generate any list from any source (database or text file). Code for list creating from the file is shown below:

<?php
<html>
<
frameset rows="100,*" frameborder="1" bordercolor="#000000" framespacing="0">
<
frame name="view" src="view.php">
<
frame name="add" src="add.php">
</
frameset>
</
html>
?>

Here is the script for reading the information from the file:

<?php
$viewfile 
file("file.log");
echo
"<html><head></head><body><form action=add.php method=POST>
<input type=hidden name=action value=del><select name=posist>"
;
for (
$step=0;$step {
$positions explode(":",$viewfile[$step]);
echo
"".$positions[0]." -- ".$positions[1]."</option>";
}
echo
"</select><input type=submit value=Delete></form></body></html>";
?>

Here is the handler:

<?php
switch ($action)
{
case 
"add":
$file_size file("file.log");
$addfile fopen("file.log","a+");
$add_string = (sizeof($file_size)+1).":".$names."\n";
fwrite($addfile,$add_string);
fclose($addfile);
Header("Location: add.php");
break;
case 
"del":
$file_del file("file.log");
$file_repl fopen("file.log","w");
$step 1;
while(list(
$line_num$line) = each($file_del))
$line_pos explode(":",$line);
if (
$line_num == ($posist-1)):
else:
$line $step.":".$line_pos[1];
fwrite($file_repl,$line);
$step++;
endif;
}
fclose($file_repl);
echo
"<a href=view.php target=view>Return to the list</a>";
break;
default:
echo
"<a href=view.php target=\"view\">Refresh the list</a><br><form action=".$PHP_SELF."
method=POST><input type=hidden name=action value=add>Your name: <input type=text name=names>
<input type=submit value=ADD>"
;
break;
}
?>

You can download the example of the script here.


 
  • Top