We use forms in the web all the time.
This is how we can create a basic form using PHP.
We need to create a class describing the form first.
In a "Form.class" file we can add the following code:
<?php
class Form
{
private $fields = array();
private $actionValue;
private $submit = "Submit Form";
private $Nfields = 0;
function __constructor($actionValue,$submit)
{
$this->actionValue = $actionValue;
$this->submit = $submit;
}
function displayForm()
{
echo "\n<form action='($this->actionValue)' method='POST'>\n";
for($j=1;$j<=sizeof($this->fields);$j++)
{
echo "<p style='clear: left; margin: 0; padding: 0; padding-top: 5px'>\n";
echo "<label style='float: left; width: 20%;'> {$this->fields[$j-1]['label']}: </label>\n";
echo "<input style='width: 200px' type='text' name='{$this->fields[$j-1]['name']}'></p>\n";
}
echo "<input type='submit' value='{$this->submit}' style='margin-left: 25%; margin-top: 10px'>\n";
echo "</form";
}
function addField($name,$label)
{
$this->fields[$this->Nfields]['name'] = $name;
$this->fields[$this->Nfields]['label'] = $label;
$this->Nfields = $this->Nfields + 1;
}
}
?>
To use the form defined above we need to create a php file as follows:
<?php
require_once("Form.class");
echo "<html><head><title>Phone form</title></head><body>";
$phone_form = new Form("process.php","Submit Phone");
$phone_form->addField("first_name", "First Name");
$phone_form->addField("last_name", "Last Name");
$phone_form->addField("phone", "Phone");
echo "<h3>Please fill out the following form:</h3>";
$phone_form->displayForm();
echo "</body></html>";
?>
After adding this to a file named "formexample.php, make sure that you add the "Form.class" file in to the same location.
Run the "form example.php" file and check your newly created form.
No comments:
Post a Comment