PHP syntax and structure for radio button and its values - php

Radio box code:
<input
type = "radio"
name = "choice"
value = "A" />Apples />
<input
type = "radio"
name = "choice"
value = "B" />Oranges<br />
$choice=array("A"=>1.00, "B"=>0.80);
echo $choice["A"]; // will give me the value of 1.00
echo $choice["B"]; // will give me the value of 0.80
Given the code snippet above, is there anything wrong in terms of either the HTML radio box, the array or the choices?

Nope, that looks perfectly fine.
Except for the random /> after your Apples text, but I suspect this is a typo?
You may also want to consider this. Probably what you are heading towards? :)
<?php
$choices = array("A"=>1.00, "B"=>0.80);
if(in_array($_REQUEST['choice'], array_keys($choices))) {
echo $choices[$_REQUEST['choice']];
}
else {
echo "Invalid choice received!";
}
?>
This would be the code that receives your radio choice. It makes sure the choice is valid and then prints it.

As far as i understood your question, PHP Code seems to be wrong. You have not specified an array in your html code which is done using [ ].
This is what you do in you php code to echo the selection of the radio:
echo $_REQUEST['choice'];
This will echo selected radio buttons value either A or B.

I'm not sure what are you trying to achieve, but there are several things that need your attention.
First of all, check the syntax of <input>: http://www.w3schools.com/html/html_forms.asp
So I'd change your html code to:
<form ... >
<input type="radio" name="choice" value="1.00" /> Apples
<br />
<input type="radio" name="choice" value="0.80" /> Oranges
</form>
And on server side, after actually submitting the form, just look for $_POST[ "choice" ] for your desired value (1.00 or 0.80).

Related

Parse radio button postback data using PHP

I have a question related to php. If anyone have an idea,please share with me. (I am a beginner in php).
I received a button value from an HTML page and displayed corresponding figure in the second page using code "param1.php". In the same program itself ( ie, "param1.php"), there is a set of radio box and i need to receive the radio value using another php program. But here i have confusion how to receive the radio value using another php program say "param2.php". also how the page redirect (to the php program where i receivvee the radio value) on selecting a radio button.
Thanks
I attach the "param1.php" below,
<!DOCTYPE html>
<html>
<body>
<br>
<?php
$data = $_POST['btn'];
$data2=$data.".png";
?>
<img src="<?php echo $data2;?>">
<h3>SCALE</h3>
<input type="radio" name="group1" value="5,10,15" checked> 5,10,15<br>
<input type="radio" name="group1" value="5,9,13"> 5,9,13<br>
</body>
</html>
No form tags
There are no form tags, so your radio tags won't get POST'd to param2.php
<form action="param2.php" method="POST">
<input type="radio" name="group1" value="5,10,15" checked> 5,10,15<br>
<input type="radio" name="group1" value="5,9,13"> 5,9,13<br>
<input type="submit" value="Process" />
</form>
Incorrect $_POST key
Now, in your param2.php file, you will be able to get the value of POST['group1']. In your code you're using the wrong key. btn doesn't exist within $_POST (in the code you've given anyway). The radio button name is group1, so access it as such;
$data = $_POST['group1'];
The value of $data will either be 4,10,15 or 5,9,13. Ensure you've got an image named 4,9,13.png and 4,10,15.png else your image won't show. Because they're comma separated, I'm going to assume these are unique file names. So;
foreach( explode(",", $_POST['group1']) as $file) {
echo "<img src='". $file .".png' />";
}
Also, ensure you do some checks on the posted data to validate the user input

How to validate multi-checkbox state?

I am using position absolute's validation engine for my form. I would like to check whether at least one checkbox from group is selected. In examples it is done by setting the same name attribute for group of checkboxes.
I cannot name checkboxes with the same name, because I am saving their state in database with following code:
$values = array(
'checkbox1' => null,
'checkbox2' => null
);
foreach (array_intersect_key($_POST, $values) as $key => $value) {
$values[$key] = mysql_real_escape_string($value);
}
$query_add_candidate=sprintf("INSERT INTO dbase (checkbox1, checkbox2) VALUES ('$values[checkbox1]', '$dates[checkbox2]')"
Now checkbox1 and checkbox2 are validated individually, beacuse they have different names. How can I check if selected is at least one of them?
Here is my HTML code:
<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox1" id="maxcheck1" value="1"/> Text1
<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox2" id="maxcheck2" value="2"/> Text2
on php ,
if(!$_POST['checkbox1'] && !$_POST['checkbox2']){
echo 'Error check at least one';
}
but what you really want is an array,
HTML,
<input type="checkbox" value="ch1" name="check[]" />
<input type="checkbox" value="ch2" name="check[]" />
php
<?php
if(empty($_POST['check'])){
echo 'Error: hey, check at least one will you!?';
}
?>
so this way you don't have to check all of them one by one, especially if you have loads of them on the same page.
NOTICE: You should also know, if checkbox is not ticked it will also not be set on the php $_POST superglobal, otherwise if it is ticked, it will show whatever the value="..." holds,
if its posted then its checked,
so if you have it in $_POST["checkbox_name"] then its checked, otherwise it wont be posted.
You can either add loads of code to reimplement control arrays in a poor way, or you can alter the code that builds your query so it can accept control arrays.
I would prefer the latter.

radio button value in php

I'm trying to make a simple survey in php
I have a set of radio buttons on a page called sja.php that sends its to sjamail.php page
the problem is that when I go to get
$answer = $_POST['ans'];
I can't seen to do anything like
echo "$answer";
but if I were to throw some logic at it
like
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
It will display correct or incorrect (edit: The if/else works correctly and will display the correct answer )
so why is it I can't access the value of the radio button "ans" as a string?
http://www.markonsolutions.com/sja.php
print_r($_POST); will return Array ( [ans] => )
Perhaps the value is something other than text.
Try
var_dump($answer);
or
print_r($answer, TRUE);
Your page works correctly if you select any of the first 4 radio buttons (ans1/2/3/4). But the rest of the radio buttons next to all those images have blank values, which would explain why your posted value is empty if you selected any of those to test with.
You need to make sure that the field in HTML has...
<input type="radio" name="ans" value="ans1" />
<input type="radio" name="ans" value="ans2" />
Also make sure your form method is POST
I had a similar problem with the following:
<input name="03 - Gender" type="radio" value="Masculino"/>Male<br/>
<input name="03 - Gender" type="radio" value="Femenino" required="required"/>Female <br/>
<input type="hidden" name="03 - Gender" value=""/>
but when I removed the third input line (the hidden one) the problem desapeared.
Try this:
$answer = (string)$_POST["ans"];
echo $answer;
You must convert $_POST["ans"] to string.

displaying all form field names but checkbox's and radios fields dont show

i have an html form full of text fields, checkbox's , and radio fields.
i wanted to get all the names of the fields so that i can get started in validating the information in them.
the method i am using to get them is
if(isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
print $name."<br/>";
}
}
but i noticed that it only displays textbox and textarea field names and it doesnt include checkbox and radio field names through this submission. do i need to include anything for it to grab the field names of those?
Checkboxes and radio buttons work a little differently than your standard inputs. If a checkbox is present on a form that doesn't necessarily mean that it will be available in the resulting POST information. Rather, those values will only be avialable if they are actually marked (checkboxes checked and radio buttons selected). The proper way to test for their value in PHP is not to check the field value but rather to check isset() first.
For a checkbox:
$data['my_checkbox'] = isset($_POST['my_checkbox']) ? 'on' : 'off';
and for a radio button:
$data['my_radio'] = isset($_POST['my_radio']) ? $_POST['my_radio'] : false;
To be a little more descriptive let's say you have the following form:
<form action="test.php" method="post">
<input type="text" name="email" value="" />
<input type="checkbox" name="active" value="Yes" />
<input type="submit" value="Submit" />
</form>
If I were to submit that form with an email value of 'test#email.com' but not check the checkbox I would have the following in $_POST:
Array (
'email' => 'test#email.com'
)
However, if I were to submit the same form with the same email address and check the checkbox I would have the following:
Array (
'email' => 'test#email.com',
'active' => 'Yes'
)
Hope that helps.
0./ Try using the following code to see the raw posted data:
echo '<pre>';
print_r($_POST);
echo '</pre>';
1./ Make sure you use a name attribute value for your checkbox and radio inputs.
Typically for checkboxes, it will be an array.
<input type="checkbox" id"=fruit-apple" name="fruits[]" value="apple" />
<input type="checkbox" id="fruit-pear" name="fruits[]" value="pears" />
2./ Make sure they sit inside the form tag.
3./ If you submit using a javascript call, try disabling javascript and see if the error stays. If it does not, you know your javascript is the culprit.

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories