PHP form data binding
I am working on a project that has a lot of user input forms. Forms are used to submit entries to MySQL database. Submitting values to forms and processing them trough some PHP logic is no news for PHP.
The problem I encountered while developing my application was the mapping of values from database to $_POST variables and vice verse. This may not sounds like a that big of a deal but when you have more than a dozen of functions returning array of information that needs to be edited trough forms that mapping all those can be a overkill task.
Let’s suppose we have a function executeSomeQuery() which executes some database query and returns results in array.
Something like
class DBActions {
public static function executeSomeQuery() {
$data = null;
$sql = // Some SQL to execute on database
$data = // executeAndGetResult($sql)
$data['name'] = 'Some cool name';
$data['lastname'] = 'Cooler last name';
$data['age'] = '25';
$data['phone'] = '00 385 95 xxx xxx';
$data['web'] = 'http://activecodeline.com';
$data['email'] = 'some.email@address.com';
return $data;
}
}
If we where to create some edit (update) form for this data, we would need six text input fields and one submit field. In order to populate those fields on some EDIT link click we would do something like
$data = DBActions::executeSomeQuery(); // this would be array
Then we would use this $data variable to set default values of input fields before we do any submit.
Something like
if ( this is not submit ) {
$name = $data['name']
….
}
Where our form input fields are formed as
label for="name">Name input type="text" id="name" name="name" value="”
and something like
if ( this is submit ) {
$data['name'] = $_POST['name'];
...
}
Then execute update by passing (array) $data to some function that executes update. Mapping all those $data['name'] = $_POST['name']; can become huge time vaster and error prone. Here is a few code shorter solution.
$data = null;
if(empty($_POST)) {
$data = DBActions::executeSomeQuery();
extract($data);
}
if(isset($_POST['submitBtn'])) {
$data = array_merge(DBActions::executeSomeQuery(), $_POST);
extract($data);
}
By doing this we have covered all of the mapping concerning the PHP side of the code. All you need to do is to write HTML form by naming the input fields like the array keys in your database query result return function.
Feel free to download and checkout the provided example.
Another case where this might get useful are the forms with multiple submit buttons. Let’s say you have file upload button on the form with lots of other input fields. When you upload the button, all your fields would get reset, so every value you entered prior to clicking the file upload button would be lost unless you set all those mappings.
In short, just imagine you have 20 of the input fields on each form and about 5-10 forms. This method would save you a lot of time.







Recent comments