Validating radio buttons in php - php

I'm new to PHP and trying to write code to test whether or not a user has clicked a radio button in response to a survey question. There are numerous radio buttons. If they haven't clicked on one then I'd like to issue an error to the user. I've tried a couple of approaches, but haven't found anything that works. Here is my current code and the error message I get. For the PHP script, I've tried all of the three following examples:
....
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
$degree_type = ($_POST['degree_type']);
} else if ($_POST['degree_type'] == null) {
$errors[] = 'Please select a degree type.';
}
if (isset($_POST['degree_type'])) {
$errors[] = 'Please select a degree type.';
} else {
$degree_type= $_POST['degree_type'];
}
if (array_key_exists('degree_type', $_POST)) {
$degree_type = ($_POST['degree_type']);
} else {
$errors[] = 'Please select a degree type.';
}
....
Here is my html, located in the same page and below the PHP.
<table>
<tr>
<td class="span6">What type of degree?</td>
<td class="span6">
<input type="radio" name="degree_type" value="MA"
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
>MA
<input type="radio" name="degree_type" value="MS"
<?php if (($_POST['degree_type']) == 'MS') {echo 'checked="checked"';} ?>
>MS
<input type="radio" name="degree_type" value="MBA"
<?php if (($_POST['degree_type']) == 'MBA') {echo 'checked="checked"';} ?>
>MBA
<input type="radio" name="degree_type" value="JD"
<?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?>
>JD
</td>
</tr>
ETC....
I get an "undefined index" error on each of the HTML lines referencing a radio button. I understand this might be easier to do in JavaScript, but I don't know much about JS... A detailed response would be much appreciated!
Thanks!

If you're getting an undefined error on the HTML page, just can add an isset() check to the logic where you're printing out the value. E.g.:
<input type="radio" name="degree_type" value="JD" <?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?> >JD
Becomes
<input type="radio" name="degree_type" value="JD" <?php if (isset($_POST['degree_type']) && $_POST['degree_type'] == 'JD') {echo 'checked="checked"';} ?>>JD

An 'undefined index' error in PHP means that you are using an undefined variable in an expression. So for example, when you did:
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
$_POST['degree_type'] was undefined. There's a couple of different possible reasons why the variables are undefined. I'd have to see the rest of the PHP file to know the exact cause.
One reason could be that the form was not properly submitted. Another reason could be that the expression was evaluated before the form was submitted.
Either way, the code below should work. Note that I'm checking if each field is set before attempting to validate it or compare it's value.
NOTE:
Obviously you have to have a proper HTML doctype, opening and closing body tags etc. The HTML in this example is only the form portion of the page.
<!-- myform.php -->
<form name="my-form" method="POST" action="/myform.php">
<span>What degree do you have?</span>
<label for="bs">BS</label>
<input type="radio" name="degree" id="bs" value="BS" <?php if(isset($degree) && $degree == 'BS') echo 'checked="checked"';?> />
<label for="ma">MA</label>
<input type="radio" name="degree" id="ma" value="MA" <?php if(isset($degree) && $degree == 'MA') echo 'checked="checked"';?> />
<label for="phd">PHD</label>
<input type="radio" name="degree" id="phd" value="PHD" <?php if(isset($degree) && $degree == 'PHD') echo 'checked="checked"';?> />
<span>Which do you like better?</span>
<label for="steak">steak</label>
<input type="radio" name="food" id="steak" value="steak" <?php if(isset($food) && $food == 'steak') echo 'checked="checked"';?> />
<label for="lobster">lobster</label>
<input type="radio" name="food" id="lobster" value="lobster" <?php if(isset($food) && $food == 'lobster') echo 'checked="checked"';?> />
<input type="hidden" name="submitted" value="submitted" />
<input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
$errors = array();
if (isset($_POST['degree'])) {
$degree = $_POST['degree'];
} else {
$errors[] = 'Please select your degree type.';
}
if (isset($_POST['food'])) {
$food = $_POST['food'];
} else {
$errors[] = 'Please select your food preference.';
}
if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
echo 'Thank you for your submission.';
}
}
?>

The reason you see these notices is because $_POST['degree_type'] is simply not set. Either by typo, or it just didn't get submitted (because you didn't select any before submitting the form).
Also note,
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
It doesn't work that way. This will check that $_POST['degree_type'] == "MS" OR: "MS" is truthy (always true) OR "MA" is truthy (always true)... see where I'm heading?
if (in_array($_POST['degree_type'], array("MS", "MA", "MBA", "JS", "PhD")) {
Is a better alternative.
Unrelated:
You should really use <label> elements to markup your labels. Example:
<label><input type="radio" name="degree_type" value="MA"> MA</label>.
This will have MA clickable.

When a form is submitted with no member of a radio button group (defined as the group of radio buttons whose name attributes are the same) selected, the submitted data doesn't include that name at all.
This is why you're getting the "undefined index" error (actually a notice); when you test the value of $_POST['degree_type'], and no radio button named "degree_type" was selected, $_POST['degree_type'] doesn't exist at all.
Fortunately, this simplifies your validation task. By calling array_key_exists('degree_type', $_POST), you can find out whether or not the key is present, and thus whether or not a radio button was selected, without prompting the PHP "undefined index" notice. If the function call returns true, you know that a radio button was selected; otherwise, you know one wasn't, and that's what your validation is trying to determine. Therefore:
if (array_key_exists('degree_type', $_POST)) {
$degree_type = $_POST['degree_type'];
}
else {
array_push($errors, "Please select a degree type.");
};
will cleanly accomplish your task.

//set a default
$degree_type = "";
if (isset($_POST['degree_type'])) {
$degree_type = $_POST['degree_type'];
} else {
$errors[] = 'Please select a degree type.';
}
Then instead of using
if (($_POST['degree_type']) == 'MA')
for your checks, use:
if($degree_type == 'MA')
undefined index means that the key you are using hasn't been initialized. So $_POST['degree_type'] won't appear until after the first time the form is submitted.

Related

Radio buttons and IF statements

I have a form of radio buttons, I want some code to run that depends on which radio button is chosen. Originally I did this by making the "name" different for each choice, but it causes problems as the names of each radio button should be the same.
Here's a form code example
<li><label for="vsat">YES</label><input type="radio" name="camp" id="vsat" value="vsat" ></li>
<li><label for="vsat2">NO</label><input type="radio" name="camp" id="vsat2" value="vsat2" ></li>
So there's two options, yes or no. I want it to echo "You chose YES" if yes is chosen and "You chose NO" if no is chosen.
Here's how I'm trying to do it
if(isset($_POST['vsat'])){
echo "You chose YES";
}elseif(isset($_POST['vsat2'])){
echo "You chose NO";
}
Make sense? I'm not even sure if it is possible the way I'm trying
You should be checking the value of the $_POST['camp'] variable:
if ($_POST['camp']) == 'vsat') {
echo "You chose YES";
} elseif ($_POST['camp'] == 'vsat2') {
echo "You chose NO";
}
The names of the variables are passed as $_POST variables when you submit the form, not the IDs.
The value of the selected radio button ('vsat' or 'vsat2') will be assigned to $_POST['camp'], while 'camp' is the name of the radio-buttons:
if (isset($_POST['camp']) && $_POST['camp']=='vsat') {
echo "You chose YES";
} elseif (isset($_POST['camp']) && $_POST['camp']=='vsat2') {
echo "You chose NO";
}
PS: the isset() is there to prevent a NOTICE popping up if none of the two radio buttons is checked. $_POST['camp'] will be undefined in this case.
I think you need change your code like this:
if ($_POST['camp'] == 'vsat') {
echo "You chose YES";
}
elseif ($_POST['camp'] == 'vsat2') {
echo "You chose NO";
}
Becouse the value you will check in radio-button-group will be sent to your PHP-script within variable $_POST['camp'] ('camp' is the name-parameter of radio-button). It will contain value 'vsat' or 'vsat2'.
this php code
<?php
if(isset($_POST['submit_btn'])){
echo $_POST['camp'];
if($_POST['camp']=='vsat'){
echo "You chose YES";
}else{
echo "You chose NO";
}
}
?>
this is form
<form method="post" action="">
<li><label for="vsat">YES</label><input type="radio" name="camp" id="vsat" value="vsat" ></li>
<li><label for="vsat2">NO</label><input type="radio" name="camp" id="vsat2" value="vsat2" ></li>
<li><input type="submit" name="submit_btn" /></li>
</form>

How to validate a checkbox input using PHP?

I have two check boxes in my form:
<div class="label-input-wrapper pickup">
<div class="form-label">I need Airport pick-up</div>
<div class="form-input">
<input type="checkbox" name="pick_up" value="Yes" />Yes
<input type="checkbox" name="pick_up" value="No" />No
<div class="error-msg">
<?php if(isset($errors['pick_up_no'])) { echo '<span style="color: red">'.$errors['pick_up_no'].'</span>'; } ?>
</div>
</div>
</div>
Variable that saves the value of the above check boxes: $pickup = $_POST['pick_up'];
Validation:
//Check the airport pickup and make sure that it isn't a blank/empty string.
if ($pickup == ""){
//Blank string, add error to $errors array.
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
}
if (($pick_up = Yes) && ($pick_up = No)) {
//if both selected, add error to $errors array.
$errors['pick_up_no'] = "Can not select Yes and No together!";
}
But the above validation just printing Can not select Yes and No together! if both are NOT selected, or if only one selected or even both are selected. It gives same error message for all the selections. Why?
You're presently assigning with a single = sign instead of comparing == with
if (($pick_up = Yes) && ($pick_up = No))
you need to change it to
if (($pick_up == "Yes") && ($pick_up == "No")){...}
while wrapping Yes and No inside quotes in order to be treated as a string.
Edit:
Your best bet is to use radio buttons, IMHO.
Using checkboxes while giving the user both Yes and No options shouldn't be used; it's confusing.
It should either be Yes OR No and not and.
<input type="radio" name="pick_up" value="Yes" />Yes
<input type="radio" name="pick_up" value="No" />No
That is the most feasible solution.
I don't know why you need a checkbox for this (this is what radio button's are supposed to do), but you can do it something like:
if(!isset($_POST['pick_up']) || count($_POST['pick_up']) > 1) {
echo 'please select at least 1 choice';
} else {
echo $_POST['pick_up'][0];
}
Then make your checkbox names:
name="pick_up[]"
Or if you really need to have separate error messages. Do something like this:
$errors['pick_up_no'] = '';
if(!isset($_POST['pick_up'])) {
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
} elseif(count($_POST['pick_up']) > 1) {
$errors['pick_up_no'] = "Can not select Yes and No together!"; // weird UX, should have prevented this with a radio button
}
if($errors['pick_up_no'] != '') {
echo $errors['pick_up_no'];
} else {
echo $_POST['pick_up'][0];
}
It is impossible for $_POST['pick_up'] to be both yes and no at the same time since the name is pick_up and not pick_up[] <- pointing to multiple variables. So it will either be yes or no either way because one parameter will overwrite the other. You would have to use javascript to verify only one is checked before submit in that case.
Use array of checkbox field elements;
<input type="checkbox" name="pick_up[]" />Yes
<input type="checkbox" name="pick_up[]" />No
then in your PHP script:
<?php
$pick_ups=$_POST['pick_up'];
$first=isset($pick_ups[0]); //true/false of first checkbox status
$second=isset($pick_ups[1]); //true/false of second checkbox status
?>
Again, as you've already been told, you should use radio-buttons for this purpose! Take into account that $_POST does not send checkbox if it is not set (check with isset($_POST['name'])

PHP Radio Buttons - Keep The Values in The Form after an Error

I'm building a contact page with email, name, etc. in HTML with PHP. I have radio buttons on my contact page as well. If the user submitted their name and checked a radio button but forgot to put an email in, the form processing page will flipped them back to the contact page with an error. I'm able to have my contact keep the values put in for their name (and email if user inputs it), but it does not keep the value checked in the radio button.
I'm new to PHP, so I bet it's a silly error on my part. Here's what I have for my Name Input:
Your Name:
<input type="text" name="name" <?php
if (isset($form['name'])) {
echo 'value="';
echo htmlentities($form['name']);
echo '"';
}
?>/>
I tried to do something similar to my Radio. Here's what I have for my Radio:
Are you New to our Business?<br>
<input type="radio" name="customer" value ="yes" <?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
Yes, I am!<br>
<input type="radio" name="customer" value="no"<?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
No, I am a returning customer!
I'm storing the values on the user input in an array called $form - that's why I have ($form['name]). I would like to it to continue doing that. Some other responses I have researched simply have an isset without the array part.
Hopefully I've provided enough information... Thanks for your help!
You need to do it like this:
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked="checked"';
}
and
if (isset($form['customer']) && $form['customer'] == "no") {
echo 'checked="checked"';
}
You need to change the if-conditional to the following:
<?php
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked';
}
?>/>
Replace the "yes" with "no" for the No part.

php if elseif then what?

This is my PHP code
The problem points I have mentioned in comments inside the code portion
if(isset($_POST['submit']))
{
if(isset($_POST['rdoption1']))
{
$var1 = $_POST["rdoption1"];
}
if(isset($_POST['rdoption2']))
{
$var2 = $_POST["rdoption2"];
}
if(!isset($_POST['rdoption1']))
{
$message = "Please select Option1";
}
elseif(!isset($_POST['rdoption2']))
{
$message = "Please select Option2";
}
elseif($_POST['rdoption2'] == "checkSetXY")
{
if($_POST["valXLocation"] == "")
{
$message = "You forget to enter X value.";
}
elseif($_POST["valYLocation"] == "")
{
$message = "You forget to enter Y value.";
}
} // till here all is good. I get all error messages if anything is left vacant or not clicked on radio button
elseif(empty($_POST['txtoption3'])) //this is not working //the issue is if i select rdoption1 any option and rdoption2 checkDefault next code logic work.. but next code logic does not work when i click on the radio of checkSetXY and enter x and y values.. It simply does not execute code further..
{
$message = "Please enter your name.";
}
else
{
//insert into db
}
}
This is html form with PHP echos
Here I'm getting messages where they shall be but not when I select checkSetXY value
<?php if(!empty($message)){ echo $message; } ?>
<form id="form1" name="form1" method="post" action="form1.php">
Space portion:
<input type="radio" name="rdoption1" value="RJ"/>space 1
<input type="radio" name="rdoption1" value="SM" />space 2
Pixel Location
<div class="formText">
<input type="radio" name="rdoption2" value="checkSetXY"/> Specify Location
X: <input type="text" id="locField" name="valXLocation">
Y: <input type="text" id="locField" name="valYLocation">
<input type="radio" name="rdoption2" value="checkDefault"/>Default
<input type="text" class="input" name="txtoption3">
<input type="submit" name="submit" value="Submit">
</form>
Now I'm confused why is it not taking elseif of txtoption3
Any help? Thanks in advance
That won't work because, it will be always set. So, use empty();
elseif(empty($_POST['txtoption3'])) //this is not working
Explanation
You are posting a form input. When you send it without filling anything, it just sends this value. ""
An empty string is not equal to null or not set.
Also, as Peter Szymkowski said, check out the fiddle.
Textfields are set if they are empty. You have to check with empty($_POST['txtoption3']) .
that is the else for
if($_POST['rdoption2'] == "checkSetXY")
which I guess is true so it will not go into that else

How to remember checkbox input in PHP Forms

For usability purposes I like to set up my form fields this way:
<?php
$username = $_POST['username'];
$message = $_POST['message'];
?>
<input type="text" name="username" value="<?php echo $username; ?>" />
<textarea name="message"><?php echo $message; ?></textarea>
This way if the user fails validation, the form input he entered previously will still be there and there would be no need to start from scratch.
My problem is I can't seem to keep check boxes selected with the option that the user had chosen before (when the page refreshes after validation fails). How to do this?
My first suggestion would be to use some client-side validation first. Maybe an AJAX call that performs the validation checks before continuing.
If that is not an option, then try this:
<input type="checkbox" name="subscribe" <?php echo (isset($_POST['subscribe'])?'checked="checked"':'') ?> />
So if subscribe is = 1, then it should select the box for you.
For Example, consider the following code for checkbox :-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
Then, this would remember the checkbox of "PHP" if it is checked, even if the validation for the page fails and so on for "n" number of checkboxes as shown below:-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("HTML", $_POST["course"]))) {
echo "checked";
} ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("CSS", $_POST["course"]))) {
echo "checked";
} ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("Javascript", $_POST["course"]))) {
echo "checked";
} ?> value="Javascript" />
And most importantly, do not forget to declare the "course" variable as an array at the start of the code as shown below :-
$course = array();
I have been battling how to create sticky check box (that is able to remember checked items any time you visit the page). Originally, I get my values from a database table. This means that my check box value is entered to a column on my db table.
I created the following code and it works just fine. I did not want to go through that whole css and deep coding, so...
CODE IN PHP
$arrival = ""; //focus here.. down
if($row['new_arrival']==1) /*new_arrival is the name of a column on my table that keeps the value of check box*/
{$arrival="checked";}// $arrival is a variable
else
{$arrival="";};
echo $arrival;
<b><label for ="checkbox">New Arrival</label></b>
<input type="checkbox" name ="$new_arrival" value="on" '.$arrival.' /> (Tick box if product is new) <BR><BR>
<input type="checkbox" name="somevar" value="1" <?php echo $somevar ? 'checked="checked"' : ''; ?>/>
Also, please consider sanitising your inputs, so instead of:
$somevar = $_POST['somevar'];
...it is better to use:
$somevar = htmlspecialchars($_POST['somevar']);
When the browser submits a form with a checked checkbox, it sends a variable with the name from the name attribute and a value from the value attribute. If the checkbox is not checked, the browser submits nothing for the checkbox. On the server side, you can handle this situation with array_key_exists(). For example:
<?php
$checkedText = array_key_exists('myCheckbox', $_POST) ? ' checked="checked"' : '';
?>
<input type="checkbox" name="myCheckbox" value="1"<?php echo $checkedText; ?> />
Using array_key_exist() avoids a potential array index undefined warning that would be issued if one tried to access $_POST['myCheckbox'] and it didn't exist.
You may add this to your form:
<input type="checkbox" name="mycheckbox" <?php echo isset($_POST['mycheckbox']) ? "checked='checked'" : "" ?> />
isset checks if a variable is set and is not null. So in this code, checked will be added to your checkbox only if the corresponding $_POST variable has a value..
My array has name="radioselection" and value="1", value="2", and value="3" respectively and is a radio button array... how to I check if the radio value is selected using this code
I tried:
<?php echo (isset($_POST['radioselection']) == '1'?'checked="checked"':'') ?> />

Categories