2017-10-07 19:27
浏览 55

为什么在没有选择它们时,HTTP POST方法的$ _POST超全局数组中缺少表示单选按钮的键?

I've written following PHP code :


      // define variables and set to empty values
      $name = $email = $gender = $comment = $website = "";

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
        echo "<pre>";
        echo "</pre>";

    <h2>PHP Form Validation Example</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
      Name: <input type="text" name="name">
      E-mail: <input type="text" name="email">
      Website: <input type="text" name="website">
      Comment: <textarea name="comment" rows="5" cols="40"></textarea>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="submit" name="submit" value="Submit">  

When I submitted the form without entering data in any of the form firled or selecting any of the two radio buttons that are present on the HTML form I got following result :

    [name] => 
    [email] => 
    [website] => 
    [comment] => 
    [submit] => Submit

In above result, I could see the names of all input form controls, even the key representing the text-area is also present within the $_POSTarray. The only expected thing that is missing from the above $_POST array output is the key representing the radio buttons 'gender'

This is my doubt. Why it's going missing from the output of $_POST array?

When I fill in the form controls, select any of the radio buttons everything works fine, no issues with it.

Are there any other similar HTML form controls which behave like radio buttons are behaving in above code which I have written?

Please someone clear my doubt and explain me the reason behind this behavior.

Thank You.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwo7858 2017-10-07 19:32

    Because when you don't select a radio input, no data is sent to the server. As shown in the MDN:

    Note: If no radio button is selected when the form is submitted, there is no value submitted to the server to represent the unselected state (e.g., value=unselected); the value is not submitted to the server at all.


    解决 无用
    打赏 举报

相关推荐 更多相似问题