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 . ' ';
}
}
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 need to insert more than one values in checkbox but now it is seemed to be only the last value am entering is inserting to database.
this is my HTML code
<input id="option5" type="checkbox" name="product[]" value="<?php echo $result["software"];?>">
<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>
and code for insertion is
$array = array($_POST['product']);
$value = implode(',', $array);
echo $value;
If you want to save multiple values in database then you need to create multiple checkboxes in html and then save the values with implode() method as below:-
<input id="option1" type="checkbox" name="product[]" value="value1">
<label for="option1">Value1</label>
<input id="option2" type="checkbox" name="product[]" value="value2">
<label for="option2">Value2</label>
<input id="option3" type="checkbox" name="product[]" value="value3">
<label for="option3">Value3</label>
now to store in database you can use implode() method.
$values=implode(",",$_POST['product']);
now store the $values in the database.
If i understand your problem you are looking for something like this:-
$array= array(
'0' => 123,
'1' => 456,
'2' => 789,
); // this is your post product array oryou want to get last value of that arrray
-----Or----
$array = $_POST['product']; // your post data after submission
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
echo $array[$key]; // 789
Hope it helps!
Your problem is likely:
You have multiple checkboxes.
And you want to insert all of them into database.
You need to loop your posted checkboxes.
Your problem is likely that you are not looping over the $_POST['product'], so, only, the last product is inserting into database.
So, your checkboxes:
<input id="option5" type="checkbox" name="product[]" value="<?php echo $result["software"];?>">
<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>
The code for posted file:
if (! empty($_POST['product'])) {
foreach ($_POST['product'] as $product) {
// Here, you insert $product into database.
}
}
I can't get this to work. I need to update many records in 1 column, based on what's checked and filled out. I tried different combinations of checking and unchecking and having the text fields blank or not blank, and in this php post code i tried many different things, but can't figure out the correct combinations and if/elses or issets or empties, etc.
the values in the checkboxes correspond to record/row IDs. all the text boxes will be prefilled with prices. all the checkboxes will be dynamically checked or unchecked. a person can undo checked checkboxes if they want or check checkboxes that are not checked. on post, all the records that are checked should get the matching text box value.
the problem is i can't get the 2 arrays to match in my post. for example, in this sample set of fields, let's say i check the 2nd checkbox and the 4th checkbox. the records that should update and the values that should save into the column should be as follows...
2 -> 17.67
4 -> 19.84
but instead i get:
2 -> 16.95
4 -> 17.67
or this (if i remove the values from 1st and 3rd text boxes):
2 -> empty
4 -> 17.67
or this (2nd checkbox id and value missing completely)
4 -> 17.67
what am i doing wrong?
if (isset($_POST["savelist"]) && !empty($_POST["savelist"])) {
$productidcheckboxes = isset($_POST['productid']) ? $_POST['productid'] : array();
$listprices = isset($_POST['listprice']) ? $_POST['listprice'] : array();
//other things i tried
//$listprices = (empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$listprices = (!empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$productidcheckboxes = $_POST['productid'];
//$listprices = $_POST['listprice'];
$new = array();
for ($i=0; $i<count($productidcheckboxes); $i++) {
$new[] = $productidcheckboxes[$i];
$new[] = $listprices[$i];
}
$k=0;
foreach ($new as $value) {
$k++;
if($k==1){
$theid = $value;
}
if($k==2){
$thelistprice = $value;
//different ifs i tried
//if ($theid<>"")
//if ($value<>"")
//if ($theid<>"" && $thelistprice<>"")
//if ($theid<>"" && $value<>"")
if ($thelistprice<>"")
{
echo $theid.": ";
echo $thelistprice."<br>";
//update table with the list prices
//mysql_query("UPDATE table_name SET mylistprices = '$thelistprice' WHERE id = $theid");
}
$theid = "";
$thelistprice = "";
$k=0;
}
}
}
form looks like this
<form action="" method="post">
<input type="checkbox" value="1" name="productid[]">
<input type="text" value="16.95" name="listprice[]">
<input type="checkbox" value="2" name="productid[]">
<input type="text" value="17.67" name="listprice[]">
<input type="checkbox" value="3" name="productid[]">
<input type="text" value="18.81" name="listprice[]">
<input type="checkbox" value="4" name="productid[]">
<input type="text" value="19.84" name="listprice[]">
<input type="checkbox" value="5" name="productid[]">
<input type="text" value="16.85" name="listprice[]">
<input type="submit" value="Save List" name="savelist">
</form>
by the way, by uneven i mean all the checkboxes will have values so correct rows will be updated, but the text boxes may or may not be filled. i would like it if i didn't have to clear any values in checkboxes or text inputs. it should just update records that are checked with it's corresponding values, and ignore non-checked checkboxes and the non-checked checkboxes corresponding values. but in the end, i may have to change how it's done, but i can't solve this one.
Add hardcoded numeric values to the form names so they match up in your processing page. Right now they are random:
<form action="" method="post">
<input type="checkbox" value="1" name="productid[1]">
<input type="text" value="16.95" name="listprice[1]">
<input type="checkbox" value="2" name="productid[2]">
<input type="text" value="17.67" name="listprice[2]">
<input type="checkbox" value="3" name="productid[3]">
<input type="text" value="18.81" name="listprice[3]">
<input type="checkbox" value="4" name="productid[4]">
<input type="text" value="19.84" name="listprice[4]">
<input type="checkbox" value="5" name="productid[5]">
<input type="text" value="16.85" name="listprice[5]">
<input type="submit" value="Save List" name="savelist">
</form>
Now you know if the user checks product[4], it really is product[4]. When you leave your keys blank like productid[], that is just an anonymous spot in the array and makes it impossible to track when dealing with checkboxes that have no value unless checked.
If you check off productid[2] and productid[4] you know that the values in the listprice array are the values that go with what you have checked off:
Array
(
[listprice] => Array
(
[1] => 16.95
[2] => 17.67
[3] => 18.81
[4] => 19.84
[5] => 16.85
)
[productid] => Array
(
[2] => 2
[4] => 4
)
)
To access the values, loop through the productid but access the listprice:
foreach($_POST['productid'] as $key => $value){
echo $_POST['listprice'][$value].'<br />';
}
I am trying to figure out how to loop through multiple POST form data that is dynamically pulled from a database and re-submit the modified data to a different table. For some reason (probably old age) I can't seem to come up with a solution that works.
I am already looping out all the records from one table (call it roster) and need to submit it to another table (call it roster2). The form is something similar to this:
<form name="name" action="form.php" method="post">
<input type="text" name="name1" value="15">
<input type="text" name="attended" value="1">
<input type="checkbox" name="nameid_12" value="12">
<input type="text" name="name2" value="8">
<input type="text" name="attended" value="1">
<input type="checkbox" name="nameid_6" value="6">
</form>
The 'name' and 'nameid' fields will always change and the number of records displayed will always be different (one day it could be 5 and the next 100).
What is the best way to loop through the POST data to submit it to the database keeping all the associations intact?
I am relatively new to working with PHP and I can't seem to figure out a good way to do this.
If you're going to generate them dynamically, I would recommend using PHP to place the ID of each form in the inputs on that form. So your original form would end up with these names:
<input type="text" name="name[12]" value="15">
<input type="text" name="attended[12]" value="1">
<input type="checkbox" name="nameid[12]" value="12">
<input type="text" name="name[6]" value="8">
<input type="text" name="attended[6]" value="1">
<input type="checkbox" name="nameid[6]" value="6">
Then your arrays will have keys corresponding to their form's ID. The array structure looks like this.
Array (
[name] => Array ( [12] => 15, [6] => 8 )
[attended] => Array ( [12] => 1, [6] => 1 )
[nameid] => Array ( [12] => 12 [6] => 6 )
)
Now we need to figure out which ids are actually present today. The array_keys() function generates an array of keys from any source array. Keys will be the same for each of the three elements, so I arbitrarily take the keys from [name].
$id_array = array_keys($_POST['name']);
Then, to access each element of the POST array, we'll use a foreach.
foreach ($id_array as $id) {
//assign variables
$name = $_POST['name'][$id];
$attended = $_POST['attended'][$id];
$nameid = $_POST['nameid'][$id];
//store
//Using whichever database style you like. I prefer PDO.
}
You can loop through the fields and retain their keys like so:
foreach ($_POST as $field_name => $field_value) {
// Storage
}
i have a check box list that some limited check boxes can be selected. for this i set the name attr of all them "answer" to work with the js function properly(i got the function from some where).
<?php
else if($result['type'] == "multipleChoice"){
echo'
<div><input type="checkbox" name="answer ans1" value="'.$res['probAns1'].'"/><input type="text" class="prob-ans" name="prob-ans1" value="'.$res['probAns1'].'"/><lable>:گزینه 1</lable></div>
<div><input type="checkbox" name="answer ans2" value="'.$res['probAns2'].'"/><input type="text" class="prob-ans" name="prob-ans2" value="'.$res['probAns2'].'"/><lable>:گزینه 2</lable></div>
<div><input type="checkbox" name="answer ans3" value="'.$res['probAns3'].'"/><input type="text" class="prob-ans" name="prob-ans3" value="'.$res['probAns3'].'"/><lable>:گزینه 3</lable></div>
<div><input type="checkbox" name="answer ans4" value="'.$res['probAns4'].'"/><input type="text" class="prob-ans" name="prob-ans4" value="'.$res['probAns4'].'"/><lable>:گزینه 4</lable></div>
';
?>
first is it correct to set two value for name attr. i did it but didnt work. like it isnt acceptable the second value.
if not how can i specify them if i have just name="answer"? i want to set some values in php if one of these check boxes is set.
<?php
if($result['type'] == "multipleChoice"){
$question->probAns1 = mysql_real_escape_string($_POST['prob-ans1']);
$question->probAns2 = mysql_real_escape_string($_POST['prob-ans2']);
$question->probAns3 = mysql_real_escape_string($_POST['prob-ans3']);
$question->probAns4 = mysql_real_escape_string($_POST['prob-ans4']);
if(isset($_POST['ans1'])){
$question->answer1 = $_POST['prob-ans1'];
}
}
?>
No, you can't have two names like you did. Following however is possible:
<input type="checkbox" name="answer[]" value="abc" />
<input type="checkbox" name="answer[]" value="def" />
Your $_POST will look like following (if both are checked):
array(
'answer' => array(
0 => 'abc',
1 => 'def'
)
)
You can also specify the array-keys, thus name="answer[answ1]" value="abc" will give you $_POST['answer']['answ1'] == 'abc'
Here is link of what you need to do.
In one sentence, you need to use arrays of html elements.