This question already has answers here:
Get all variables sent with POST?
(6 answers)
How to grab all variables in a post (PHP)
(5 answers)
How do I get the key values from $_POST?
(6 answers)
Retrieve post array values
(6 answers)
How to get an array of data from $_POST
(3 answers)
Closed 5 years ago.
I have an HTML-form with 3 inputs of type text and one input of type submit, where a name of an animal is to be inserted into each textbox. The data should then be inserted into a PHP-array.
This is my HTML-form:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal1" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal2" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal3" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
And this is my much experimental PHP-code:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1"];
$farmAnimals = $_POST["animal2"];
$farmAnimals = $_POST["animal3"];
}
// As a test, I tried to echo the saved data
echo $farmAnimals;
?>
This does not work, as the data doesn't magically turn into an array, unfortunately, which I thought it would.
I have also tried this:
<?php
if (isset ($_POST["send"])) {
$farmAnimals = $_POST["animal1", "animal2", "animal3"];
}
echo $farmAnimals;
?>
This gives me an error message. How can I insert this data into a PHP-array?
First initialize the $farmAnimals as array, then you can push elements
if (isset ($_POST["send"])) {
$farmAnimals = array();
$farmAnimals[] = $_POST["animal1"];
$farmAnimals[] = $_POST["animal2"];
$farmAnimals[] = $_POST["animal3"];
print_r($farmAnimals);
}
Try this:
$string = "";
foreach($_POST as $value){
$string .= $value . ",";
}
Or this:
$string = implode(',', $_POST);
If you change the text field names to animal[] then you have an array of animal names when it is posted
<form action='Test.php' method='post'>
<input type='text' placeholder='Enter animal one...' name='animal[]' />
<input type='text' placeholder='Enter animal two...' name='animal[]' />
<input type='text' placeholder='Enter animal three...' name='animal[]' />
<input type='submit' value='Submit' name='send' id='send'>
</form>
You can then process that array in php easily for whatever end purpose you have - the output of which would be like this:
Array
(
[animal] => Array
(
[0] => giraffe
[1] => elephant
[2] => rhinocerous
)
[send] => Submit
)
To access these animals as an array in their own right you could do:
$animals=array_values( $_POST['animal'] );
Try naming your input fields like this:
<form action="Test.php" method="post" name="myForm" id="myForm">
<input type="text" placeholder="Enter animal one..." name="animal[0]" id="animal1">
<input type="text" placeholder="Enter animal two..." name="animal[1]" id="animal2">
<input type="text" placeholder="Enter animal three..." name="animal[2]" id="animal3">
<input type="submit" value="Submit" name="send" id="send">
</form>
This way you be able to access those values in your PHP code like this:
if(isset($_POST["send"])) {
$farmAnimals = $_POST["animal"];
}
var_dump($farmAnimals);
// Array( [0] => Animal1, [1] => Animal2, [2] => Animal3 )
// Where Animal1,... are the values entered by the user.
// You can access them by $farmAnimals[x] where x is the desired index.
Tip: You can use empty() to check a variable for existance and if it has a "truthy" value (a value which evaluates to true). It will not throw an exception, if the variable is not defined at all. See PHP - empty() for details.
Futher reference about the superglobal $_POST array, showing this "array generating name" approach: https://secure.php.net/manual/en/reserved.variables.post.php#87650
Edit:
I just saw, that you actually overwrite your $farmAnimals variable each time. You should use the array(val1, val2, ...) with an arbitray amount of parameters to generate an numeric array.
If you prefer an associative array do this:
$myArray = array(
key1 => value1,
key2 => value2,
....
);
To append a value on an existing array at the next free index use this syntax:
// This array contains numbers 1 to 3 in fields 0 to 2
$filledArray = array(1,2,3);
$filledArray[] = "next item";
// Now the array looks like this:
// [0 => 1, 1 => 2, 2 => 3, 3 => "next item"]
Related
im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}
It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}
You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>
I have two inputs as follows:
<form method="post" action="#">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
/* The second input set was generated dynamically via jQuery. */
</form>
I want to pair each product with its' quantity with multidimensional array with following codes (thanks to #Styphon):
$works = $_POST['prod'];
foreach ($works as $work => $value) {
echo $value['prod'] ." ". $value['qty'] ."<br>";
}
However, the results was weird as follows
aa
11
bb
22
Appreciated if someone can help on this.
You need a multidimensional array. Something like this:
<form>
<input type="text" name="prods[0][prod]">
<input type="text" name="prods[0][qty]">
<input type="text" name="prods[1][prod]">
<input type="text" name="prods[1][qty]">
</form>
Then in PHP you can access the multidimensional array using $_POST['prods'], you can loop through each one using a foreach like this:
foreach ( $_POST['prods'] as $i => $arr )
{
echo "$i is prod {$arr['prod']} and qty {$arr['qty']}<br>";
}
This question already has answers here:
How to pass an array of checked/unchecked checkbox values to PHP email generator?
(5 answers)
Closed 9 years ago.
On my form I have this part :
<input type="checkbox" name="city" value="Nicosia" class="choosecity">Nicosia<br>
<input type="checkbox" name="city" value="Limassol" class="choosecity">Limassol<br>
<input type="checkbox" name="city" value="Larnaca" class="choosecity">Larnaca<br>
and on the results page where I use the mail function, I want to get thechecked cities.
I used this without result:
foreach($_POST['city'] as $checkbox){
echo $checkbox . ' ';
}
What am I missing here?
Use name="city[]". Otherwise you will only be able to submit one city. You may also want to use
$cities = isset($_POST['city']) ? $_POST['city'] : array();
foreach ($cities as $city)
You need to name your inputs as an array name="city[]"
PHP uses the square bracket syntax to convert form inputs into an array, so when you use name="education[]" you will get an array when you do this:
$educationValues = $_POST['education']; // Returns an array
print_r($educationValues); // Shows you all the values in the array
So for example:
<p><label>Please enter your most recent education<br>
<input type="text" name="education[]"></p>
<p><label>Please enter any previous education<br>
<input type="text" name="education[]"></p>
<p><label>Please enter any previous education<br>
<input type="text" name="education[]"></p>
Will give you all entered values inside of the $_POST['education'] array.
In JavaScript, it is more efficient to get the element by id...
document.getElementById("education1");
The id doesn't have to match the name:
<p><label>Please enter your most recent education<br>
<input type="text" name="education[]" id="education1"></p>
You just just have to add this [] to input name this will create an array starting with [0]. The result will look so:
array(
[0] => 'Nicosia',
[1] => 'Limassol',
[2] => 'Larnaca',
)
The HTML:
<input type="checkbox" name="city[]" value="Nicosia" class="choosecity" />Nicosia<br>
<input type="checkbox" name="city[]" value="Limassol" class="choosecity" />Limassol<br>
<input type="checkbox" name="city[]" value="Larnaca" class="choosecity" />Larnaca<br>
The PHP:
if( isset($_POST[city]) && is_array($_POST[city]) ){
foreach($_POST[city] as $checkbox){
echo $checkbox . ' ';
}
}
This question already exists:
how to post value of 3 input fields into database
Closed 9 years ago.
hello developers i am creating 2 text boxes and 1 select box dynamically using java script function... now i want to post the value of (n) fields created into database (relevant table)
as i am using codeigniter so m posting the script and code
this is the simple java script that i am using
<script>
var counter=1;
function generateRow() {
var count="<font color='red'>"+counter+"</font>";
var temp ="<p> <div class='_25'><input type='textbox' id='textbox' name='stop"+counter+"' placeholder='Stop Name'></input></div> <div class='_25'><input type='textbox' id='textbox' name='timing"+counter+"' placeholder='Timing'></input></div> <div class='_25'><select id='ampm"+counter+"' name='ampm"+counter+"'><option>a.m</option><option>p.m</option></select> </div>";
var newdiv = document.createElement('div');
newdiv.innerHTML = temp + count;
var yourDiv = document.getElementById('div');
yourDiv.appendChild(newdiv);
counter++;
}
</script>
and this is my division on php file
<div id="div">
</div>
<p> </p>
<div class="_25">
<p>
<input type="button" name="button" class="button red" id="button" value="Add" onclick="generateRow() "/></a>
</p>
</div>
<input type='button' value='Remove Button' id='removeButton'>
and this is my related table fields
route_number stop_name am_pm timing
My favorite way to do this is to use the DOM as much as possible. Don't use counters unless you absolutely have to (they're just a source of bugs). Here's a quick example:
Html/JS/jQuery (can vary, I crafted this to make it easy to follow):
<form method="POST" id="theForm">
<div id="fields">
<input type="text" name="fields[]"/>
</div>
<input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#addField').click(function() {
$('#fields').append(
$('<input type="text" name="fields[]"/>')
);
})
});
</script>
Note how I don't need to use any sort of counting variable. Just like PHP, you can create an array of POST variables without specifying indexes by using [] and the server (or browser? I'm not sure) will build the array for you. The order in which the <input /> fields are rendered on the page will be the order they are provided to your PHP via $_POST. This code...
foreach ($_POST['fields'] as $fieldIndex => $fieldValue) {
doStuff($fieldValue);
}
... will process each field in the order they were added. You can even use JavaScript to re-order or remove the inputs and that will be reflected in $_POST. This method, coupled with JSON encoding, makes for a fast and easy way to handle multi-input, free-form fields.
Update:
Applying the above code to your use-case requires a small addition that may not be obvious. You'll need to create an array for each of the three inputs (stop, timing, and ampm) like so:
<form method="POST" id="theForm">
<div id="fields">
<input type="text" name="fields[stop][]"/>
<input type="text" name="fields[timing][]"/>
<select name="fields[ampm][]">
<option value="am">AM</option>
<option value="pm">PM</option>
</select>
<br/>
</div>
<input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#addField').click(function() {
$('#fields').append(
$('<input type="text" name="fields[stop][]"/>'),
$('<input type="text" name="fields[timing][]"/>'),
$('<select name="fields[ampm][]"><option value="am">AM</option><option value="pm">PM</option></select>'),
$('<br/>')
);
})
});
</script>
Filling out this form with some test data yields the following array:
[fields] => Array
(
[stop] => Array
(
[0] => aaa
[1] => bbb
)
[timing] => Array
(
[0] => 1111
[1] => 2222
)
[ampm] => Array
(
[0] => am
[1] => pm
)
)
And to process that in PHP requires a simple old-school loop:
$numFields = count($_POST['fields']['stop']);
for ($i = 0; $i < $numFields; $i++) {
// Pack the field up in an array for ease-of-use.
$field = array(
'stop' => $_POST['fields']['stop'][$i],
'timing' => $_POST['fields']['timing'][$i],
'ampm' => $_POST['fields']['ampm'][$i]
);
saveToDatabase($field);
}
Unfortunately I don't have time right now to make sure all that is correct. It should be, and if its not it may still help :). I'll check back in a few hours.
name your dynamic input box "stop["+counter+"]" (using braces as part of the name) instead of adding a counter to the end of the name. Then in your post data, $_POST['stop'] will be an array of values that you can just foreach loop over with the counter as the key in the sub-array. And $_POST['stop'][1] will correspond to $_POST['timing'][1]...etc.
You can construct the following HTML input fields:
<input type="text" name="data[]" />
<input type="text" name="data[]" />
<input type="text" name="data[]" />
// ...
Which will lead to an array keyed data inside $_REQUEST super global, when you var_dump($_REQUEST['data']). Try it out. You don't even need to index the data[] array, since PHP will do it for you.
You might want to process your $_REQUEST['data'] or $_POST['data'] array with a foreach loop construct:
foreach($_REQUEST['data'] as $data){
// $data is the corresponding input field's value
}
Basically what I want my program to do is to ask the user how many numbers they want to enter. Once the value is submitted, the program will take the value and create this amount of textboxes. Each textbox will take a number and once submitted, it should take all the numbers (excluding the initial text box) and store it into an array or something so the mean can be calculated.
I've been able to get as far as creating x amount of textboxes but cannot find a way to submit these values.
<html>
<body>
<form action="means.php" method = "get">
Enter sample size: <input type = "number" name = "size" <br>
<input type = "submit">
<?php
if ( isset($_GET["size"] ) )
{
$size = $_GET["size"];
$count = 1;
while ($count <= $size)
{
echo '<br><input type=\"text\" name=\"textbox".$count."\" />';
$count++;
}
}
?>
</form>
</html>
</body>
I assume the problem is that the textboxes created are being echoed so the name "textbox.$count." cannot be used to obtain the numbers?
Any help would be greatly appreciated. Thanks in advance!
Just use PHP's array notation for form field names:
<input type="text" name="textbox[]" />
^^---force array mode
which will produce an array in $_POST['textbox'], one element for each textbox which was submitted with the textbox[] name.
e.g:
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
produces
$_POST = array(
'textbox' => array )
0 => 1,
1 => 'foo',
2 = > 'banana'
)
)
Your problem is that you're using single-quoted strings ('), meaning that
$var = 'foo';
echo '$var' // outputs $, v, a, r
echo "$var" // outputs f, o ,o