How can I handle a $_POST variable identifier as a variable? - php

Re-writing the question here so it's (hopefully) easier to understand.
I have a piece php that received a $_POST from a form. Each time a $_POST is completed, only one set of data is sent. It could be $_$POST['boat'] or $_POST['car'] or $_POST['dog'] etc. I do not know what the post will contain upon receiving it. If it is $_POST['dog'] then the value of the post will go into the $database.dog table. If it is $_POST['car'] then the value of the post will head into the $database.car table, and so on.
Once a post is made, how can I identify whether the post was called 'car' or 'dog' or 'boat' or anything else ?

There's a lot of ways to do this. Simply with ifs:
if(isset($_POST['car'])) {
// do car stuff
}
if(isset($_POST['boat'])) {
// do boat stuff
}
//etc...
Or a switch:
switch(true) {
case(isset($_POST['car'])):
// do car stuff
break;
case(isset($_POST['boat'])):
// do boat stuff
break;
//etc...
}
To avoid the ifs or switch you can use a hidden input:
<input type="hidden" name="form" value="car">
Then use $_POST['form'] to dynamically build your queries etc...
If car or boat etc... is the only key under $_POST or if it is always the first key then:
$form = key($_POST);

You can get the key/index and value and print that info if you are unsure what the keys or values will be that are coming from your form POST.
function getKeyValuePairs() {
$stmt = null;
if(isset($_POST)){
foreach($_POST as $key => $value) {
$stmt .= $key." => ".$value."<br>";
}
print_r($stmt);
}
Because $_POST is global no need to push variable into function.
HTML: run function to print key/value pairs
<div>
<?php echo getKeyValuePairs(); ?>
</div>

Related

PHP How to process a form that has dynamically generated fields?

I am trying to process a form which I don't know ahead of time what the form fields will be. Can this still be done in PHP?
For example I have this html form:
<form method="post" action="process.php">
<?php get_dynamic_fields(); // this gets all the fields from DB which I don't know ahead of time what they are. ?>
<input type="submit" name="submit" value="submit" />
</form>
And here is what I have in the PHP process file
<?php
if ( isset( $_POST['submit'] ) && $_POST['submit'] === 'submit' ) {
// process form here but how do I know what field names and such if they are dynamic.
}
?>
Here is a caveat: assuming I can't get the data from the db ahead of time, is there still a way to do this?
Sure, just iterate over all the items in the $_POST array:
foreach ($_POST as $key => $value) {
// Do something with $key and $value
}
Note, your submit button will exist in the array $_POST, so you may want to write some code to handle that.
You can iterate over all $_POST keys like this.
foreach($_POST as $key => $value)
{
echo $key.": ".$value;
}
This will give you the field names used in HTML form.
$field_names = array_keys($_POST);
You can also just iterate through the POST array using
foreach($_POST as $field_name => $field_value) {
// do what ever you need to do
/* with the field name and field value */
}
you could loop over all parts of the `$_POST array;
foreach($_POST as $key => $value){
//$key contains the name of the field
}
Get the names of the fields from your get_dynamic_fields function and pass them in a hidden input that is always an array with a static name. Then parse it to get the names of the inputs and how many there are.

Form input field validation with PHP

I have a couple of fields in the <form>... $fieldset is array of the fields name, it loop them with isset() checking.
I want to apply validation (eg: required input, email) to a few fields, how to apply this from my code logic?
public function actionProfile($id = null) {
$profileModel = new ProfileModel;
// <input> fields name
$fieldset['name'] = array('FirstName', 'LastName');
$fieldset['address'] = array('HouseNumber', 'StreetName', 'Town', 'Location');
$formError = array();
if (isset($_POST['profile'])) {
// Process input event
foreach ($fieldset as $legend => $fields) {
foreach ($fields as $field) {
if (!isset($_POST['profile'][$field])) {
$formError[$legend] = $field;
} else {
$form[$legend][$field] = $_POST['profile'][$field];
}
}
}
if (count($formError) == 0) {
if ($profileModel->saveAddress($form['address'])) {
//Saved to the database.
}
}
}
// Get data from the database
$data['profile'] = $profileModel->find($id);
$view = new View($this->layout, $data)->render();
}
In the view file, it would look something like this:
<input type='text' value=<?php echo $profile['first_name'] name='profile[FirstName]' ?>
<input type='text' value=<?php echo $profile['last_name'] name='profile[LastName]' ?>
Edit: When editing the record via form.. If there is an error (validation) - I want to put user input value back into <input> value instead of value from the database. How can it be done from my code?
You are currently putting validation logic inside the controller. That should go in the Domain Business Object (read more: here and here).
Also, "model" is not a class. Model is a layer in MVC architecture. This layers mostly consists of two types of instances: Domain Objects and Data Mappers. Each with quite different responsibilities.
I think it would be wise to split the verification code from the actual update function.
Have it run through a validator first, checking for length and required inputs. When that passes, you can send all that (formatted) data to the action. If it doesn't pass the validation, return it to the view with additional error information so you can guide the user to fix the problem.
I hope you understand what I'm trying to explain to you. :-).
Use the PHP Filter functions:
http://www.php.net/manual/en/ref.filter.php
Use the Variable Handlers
http://us2.php.net/manual/en/ref.var.php

php form multiple input

I have a PHP page with a list of items pulled from a database. Each item has an input form next to it, and right at the bottom, a submit button.
How can i do a POST check to find out which inputs have had data added? I can get the data, but how do I know the names of the particular inputs that have been filled?
Iterate over $_POST and list the keys which have nonempty values.
foreach ($_POST as $key => $value) {
if (!empty($value)) {
echo $key . " was filled in.";
}
}
Take a look at the isset() function of PHP - http://php.net/manual/en/function.isset.php.
For Example,
<?php
if(isset($_POST['somevar'])) {
// if the value has been set, this code is executed
} else {
//value not set, so execute this code.
}
?>

php form result loop

I'm trying to make a BASIC roulette script.
Is there anyway to get the submitted results of a form using PHP? In fact I know theres a way, but i can't find out how to do it.
So say if my form had several fields I want the result to loop through and show me which fields were filled and the numbers in each.
UPDATE: And say the form has about 40 fields, would I have to name each one in the loop? Any easier way?
$_GET or $_POST depending on the form method.
if(isset($_REQUEST['formInputName'])){
echo $_REQUEST['formInputName'];
}
$_REQUEST looks for GET, POST, and COOKIE.
You can also use $_GET to get a variable from the url (asdf.php?var=2).
If your form looks like this:
<form method="post" action="result.php">
<input type="text" name="foo">
</form>
In result.php you can use the global variable $_POST and loop through it if you want:
foreach($_POST as $name => $value) {
echo $name . ' = ' . $value;
}
If your form has 40 fields, you still need to name them all, but you can automate the process of naming and retrieving them with a loop. For example, if you wanted to create a sum with the value of all the fields, you could name them number1, number2, etc and do:
$sum = 0;
for($i = 1; $i <= 40; $i++)
$sum += $_POST['number' . $i];
You need to define the name of each field using name="something" in the input element, and than in the PHP you're getting it using $_POST['something'] in case you sent the form as method="post" or $_GET['something'] in case of get method
You can see what's sent using var_dump() or print_r(), just write something like that:
echo '<pre>';
print_r($_POST);
Or you can go all over the array using foreach statement:
<?php
foreach($_POST AS $key=>$val)
{
echo $key.': '.$val."<br />\n";
}
?>

PHP quiz send data to next page

ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.

Categories