0

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!

1
  • Should the second gorup of if else statements use !isset instead of isset, currently it'll show an error when there is a post value Commented Jul 31, 2013 at 15:36

5 Answers 5

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

It works, but it doesn't solve the underlying problem. Just handling the symptom!
Just to be sure... you are actually submitting the form (i.e. with a submit button), before you check for the degree type, right?
1

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

Comments

0

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.

3 Comments

Not a typo; if no member of a radio button group is selected, the key in $_POST isn't created. in_array() would therefore still produce the "undefined index" notice. Good spot regarding the logic error, though.
@AaronMiller: "Either by typo, or it just didn't get submitted", So yeah, I've said that. I'll edit to make it clearer.
Thanks, but I still get the undefined index notice. Thanks for the note regarding using a label, forgot to include that.
0

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.

3 Comments

Thanks for your explanation. Unfortunately, I still get the same error message using this approach.
Still getting the notice from your validation code, or from your form redisplay code (i.e., where you're drawing the radio buttons)?
PHP supposedly does short-circuit evaluation, meaning that something like if (array_key_exists('degree_type', $_POST) && $_POST['degree_type'] == 'MA') { ... } will only evaluate the right-hand side of the && conditional if the left side evaluates to true. Assuming that's the case, modifying the conditions in your form redisplay code to resemble that example should stop them generating "undefined index" notices.
0
//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.

5 Comments

What's happening? Is it still undefined index? Have you replaced all the if($_POST['degree_type'] == "some degree") echo " checked"; with the $degree_type?
Yes, I'm still getting the undefined index on the html. For the checks, I did replace all the if($_POST['degree_type'] with $degree_type.
Where are your if else statements contained, are they within another if statement to chekc that the form has been submitted?
Yep, they are wrapped in a conditional if (isset($POST_['submitted'])) ... statement
Place the $degree_type = ""; above that line checking for the submitted. Also just check it's $_POST['submitted']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.