set two values for an input name attribute - php

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.

Related

form checkbox group in php

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!";
?>

How do I post two uneven arrays where one set is checkboxes and the other text input boxes

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 />';
}

How to submit the values of checkbox? [duplicate]

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 . ' ';
}
}

3 checkboxes with same name and same same numeric value

Given this code:
<input type="checkbox" id="Coke" name="Price" value="70" />
<input type="checkbox" id="Fanta" name="Price" value="70" />
<input type="checkbox" id="Sprite" name="Price" value="70" />
I would like to know how, if my user selects Fanta checkbox, I want my php variable $type="Fanta" but I need form checkbox VALUES to stay NUMERIC for total price calculation.
It's not clear what exactly you're asking, but I believe you basically want 2 fields, one that defines the price and one that defines the selected type.
In that case, your best bet would be to store the prices server-side (That way people can't modify them too, which is good!). If you do this, your checkboxes will look like this:
<input type="checkbox" id="Coke" name="type[]" value="Coke" />
<input type="checkbox" id="Fanta" name="type[]" value="Fanta" />
<input type="checkbox" id="Sprite" name="type[]" value="Sprite" />
Your backend code would look like this:
$prices = array(
'Coke' => 70,
'Fanta' => 70,
'Sprite' => 70
);
$types = $_POST['type'];
$total = 0;
foreach($types as $key => $type) {
if (!isset($prices[$type]))
continue;
$total += $prices[$type];
}
// Use $total as your total price for whatever calculation
echo $total;
As per your comment, if you still want these prices client side for calculations, you can use json_encode to output it into a script tag and use the prices directly. It's basically going to turn the server-side prices array into a client-side array of prices.
<script type="text/javascript">
var prices = <?= json_encode($prices) ?>;
// Now you can use prices['Coke'] etc, based off the value of the selected checkbox.
</script>
I would like to know how, if my user selects Fanta checkbox,
Then name you field fanta:
<input type="checkbox" id="Fanta" name="fanta" value="70" />
Once you have done that you can get the values using either the $_POST or the $_GET superglobal (depending on your form method):
if (isset($_POST['fanta'])) {
echo $_POST['fanta'];
}
However you should never ever ever rely on the prices coming from the clientside!
but I need form checkbox VALUES to stay NUMERIC for total price calculation.
That is not going to happen because in HTTP values are being send as strings. Luckily PHP does automatic type juggling for you so you will still be able to do calculations with the string values.
http://codepad.viper-7.com/GOhHdz
In some situations you want to make it a integer value explicitly. In that case you can use type casting:
var_dump((int) '18');
http://codepad.viper-7.com/kJlGoS
When you post a form, anyway you will get 70 as value.
echo $_POST['Price'];
gives 70
<input type="checkbox" value="Coke" name="Price" rel=70 />
<input type="checkbox" value="Fanta" name="Price" rel="70" />
<input type="checkbox" value="Sprite" name="Price" rel="70" />
use javascript to get rel attribute value for selected checkbox for total price

PHP form processing with variableform inputs

Got a form that has the option to add many inputs for ordering pictures via picture number.
In theory a customer could order 1 picture or 100, how would I go about the PHP.
As coding up to 100 $_POST[] for each possible field seems crazy as each of the added fields as it's own unique NAME attr using jQuery.
Anyone got any bright ideas?
Using field names that end in square brackets will cause PHP to create the entries as an array:
<input name="foo[]" value="foo" />
<input name="foo[]" value="bar" />
<input name="foo[]" value="moo" />
<input name="foo[]" value="cow" />
will produce the following: $_REQUEST['foo'] (or $_POST['foo']/$_GET['foo']) is an array like this:
array(
0 => 'foo',
1 => 'bar',
2 => 'moo',
3 => 'cow'
);
You could try something like
for ($i=0;$i<100;$i++){
if (isset($_POST['picture'.$i])){
// Do something
} else {
break;
}
}
You can do something like this
<input type="checkbox" value="picnumber" name="pictures[]" />
<?php
$pics = $_POST['pictures']; // here you will get an array of values of the selected images
?>

Categories