All,
I have a form that has some text inputs, checkboxes, select box and a textarea. I want to submit the form with PHP using a submit button to a page for processing.
That part is fine but what I would like to do is basically get the results into an array so I can do a foreach loop to process the results.
Basically I'm trying to create a dynamic form the submits to my backend processing script and don't want to hard code in the post values like the following:
$var1 = $_POST['var1'];
echo $var1;
$var2 = $_POST['var2'];
echo $var2;
Does anyone know how to go about doing something like this or give any recommendations?
If there're no other data in your POST but these generated elements, just do
foreach( $_POST as $key => $val ) {
// do your job
}
and process what you have. If you want to mix your generated entries with predefined you may want to put these generated in nested array:
<input ... name="generated[fieldname]" />
and then you iterate
foreach( $_POST['generated'] as $key => $val ) {
// do your job
}
Just use array notation:
<input name="vars[]" value="" />
Then you will have something like this as $_POST:
Array ('vars' => Array(
0 => 'val1'
1 => 'val2'
)
)
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val";
}
Actually, the $_POST variable is an array. you just need to extract the array values by using a simple foreach loop. that's it.
I hope this example help you.
foreach($_POST as $field_name => $val)
{
$asig = "\$".$field_name."='".addslashes($val)."';";
eval($asig);
}
After running this script all the POST values will be put in a variable with the same name than the field's name.
Related
I have 2 pages in php. The 1st page includes a form which transimts data to the 2nd page. The form uses method=post. Data transmitted successfully in the 2nd page. I have the following code, which gets data and printing them using the code:
php?
var_dump($_POST);
foreach ($_POST as $key => $value) {
echo $value;
}
?>
All I want is to extract data from array and place them into variables, because I want to use these varaibles later in some if startments and mysql queries. Any idea how can i do this?
First, these really are basic PHP skills (or programming skills for that matter). Try to follow some tutorials or courses before attempting to write code in the "real world".
As long as you know the key for the value you want to store, this is how you do it:
$yourVariableName = $yourArray['yourKey']; // or just a number if the key is an int
You don't need for loops to do this.
EDIT
$kentroName = $_POST['kentro_name'];
$kentroSurName = $POST['kentro_surname'];
// And then the following six.
<?php
var_dump($_POST);
$array = array();
foreach ($_POST as $key => $value) {
echo $value;
$array[$key] = $value;
}
print_r($array);
?>
Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.
I have form with changable content of textareas, from 1 to 5, each time with different names. I cannot modify the form itself.
how can i get number of textareas in form and names of them (it would be the best if i could do it clean in php without javascript).
the form is using method="POST" and PHP version is 5.2+
EDIT: i forgot to tell you that i have only textareas in form.
You could do something along the lines of :
$count=0;
$formElements=array();
foreach ($_POST as $key => $val)
{
$count++;
$formElements[]=$key;
}
echo "The form as $count elements.";
var_dump($formElements);
If you want the values of the post you could make a two dimensional array like this:
foreach ($_POST as $key => $val)
{
$count++;
$formElements[]=array($key => $val);
}
if you post form to php script, $_POST variable is array. then you can use something like this:
foreach($_POST as $v){} to get every field.
I am trying to pass an array of values through a form submission. As an example:
example.com?value1=178&value2=345&value3=2356
The easy solution would be for me to do the following to get the values on the new page:
$value1=$_GET['value1'];
$value2=$_GET['value2'];
$value3=$_GET['value3'];
The difficulty that I am having is that the variable after the word 'value' passed through the form will change with each submission. So I have amended the code to pass as:
example.com?value14=178&variable=14&value23=345&variable=23&value63=2356&variable=63
As you can see here, I have now passed the variable that comes in from of the value as a GET parameter. My attempt then GET these values to display individually on the submitted page is as follows:
$variable=$_GET['variable'];
$value=$_GET['value'.$variable];
echo $value . '<br>';
This code almost works. I am able to get the last array which is passed through to display. How can I fix this code to get all of the passed values to display on the submitted page?
Use PHP's array notation for form fields:
val[]=178&val[]=14&val[]=345&etc...
This will cause $_GET['val'] to be an array:
$_GET = array(
'val' => array(178, 14, 345, etc...)
)
If you can't rearrange the URL like that, you can try using preg_grep:
$matches = preg_grep('/^variable\d+$/', array_keys($_GET));
which'll return :
$matches= array('variable1', 'variable2', 'variable3', etc...);
Use an array, for example like this without the need for variable $variable.
example.com?value[14]=178&value[23]=345&value[63]=2356
foreach ($_GET['value'] as $key => value) {
echo $key . " => " . $value . "<br/>";
}
EDIT: Another way for getting the values would be looping the whole $_GET -array and parsing values from there like this (variables are always in the form of "value" followed by X numbers):
example.com?value14=178&value23=345&value63=2356
$values = array();
foreach ($_GET as $key => $value) {
if (preg_match('/^value[\d]+$/', $key)) {
// remove "value" from the beginning of the key
$key = str_replace('value', '', $key);
// save result to array
$values[$key] = $value;
}
}
See http_build_query()
I have a PHP page that queries a DB to populate a form for the user to modify the data and submit.
The query returns a number of rows which contain 3 items:
ImageID
ImageName
ImageDescription
The PHP page titles each box in the form with a generic name and appends the ImageID to it. Ie:
ImageID_03
ImageName_34
ImageDescription_22
As it's unknown which images are going to have been retrieved from the DB then I can't know in advance what the name of the form entries will be.
The form deals with a large number of entries at the same time.
My backend PHP form processor that gets the data just sees it as one big array:
[imageid_2] => 2
[imagename_2] => _MG_0214
[imageid_10] => 10
[imagename_10] => _MG_0419
[imageid_39] => 39
[imagename_39] => _MG_0420
[imageid_22] => 22
[imagename_22] => Curly Fern
[imagedescription_2] => Wibble
[imagedescription_10] => Wobble
[imagedescription_39] => Fred
[imagedescription_22] => Sally
I've tried to do an array walk on it to split it into 3 arrays which set places but am stuck:
// define empty arrays
$imageidarray = array();
$imagenamearray = array();
$imagedescriptionarray = array();
// our function to call when we walk through the posted items array
function assignvars($entry, $key)
{
if (preg_match("/imageid/i", $key)) {
array_push($imageidarray, $entry);
} elseif (preg_match("/imagename/i", $key)) {
// echo " ImageName: $entry";
} elseif (preg_match("/imagedescription/i", $key)) {
// echo " ImageDescription: $entry";
}
}
array_walk($_POST, 'assignvars');
This fails with the error:
array_push(): First argument should be an array in...
Am I approaching this wrong?
Would it be possible to change the way the items are named on the form?
Current:
ImageID_03
ImageName_34
ImageDescription_22
Changed To:
ImageID[03]
ImageName[34]
ImageDescription[22]
This way it should come through the $_POST as three separate arrays meaning you can skip all that extra processing.
I hate to edit many rows at once. It's usability fault
If I go for it, I'd make it with such a form:
<form method="POST">
<input type="text" name="name[1]">
<input type="text" name="desc[1]">
<input type="text" name="name[2]">
<input type="text" name="desc[2]">
...etc
</form>
So, I'd have 2 arrays, $_POST['name'] and $_POST['desc'] where id used as a key
In your case I wouldn't use array_walk as it's just a syntax sugar, and make it with foreach to have full contorol over data processing.
I think you need
global $imageidarray;
to access a global array inside a function.
Something like this would work as well, assuming your three form fields are always submitted together:
$ids = preg_grep('/^imageid_(\d+)$/', array_keys($_POST)); // $ids now contains only the imageid_* keys
foreach($ids as $id) {
$id = substr($ids, 8); // now contains the numeric id of the field
echo $id, ": ", $_POST["imageid_$id"], "\n";
}
Not as efficient as using the array notation in the form names, but allows you to trivially extract just the ID numbers from one of the field names and then use it to access the other matching fields as well.