php 实例之如何获取radio单选按钮的值

时间:2016-06-18
html radio控件作为单选按钮是表示一组互斥选项按钮中的一个,当一个按钮被选中,之前选中的按钮就变为非选中的,本文章向大家介绍php如何获取radio单选按钮的值,需要的朋友可以参考一下。

HTML表单代码:

<html>
 <head>
  <title>php 实例之如何获取radio单选按钮的值</title>
 </head>        
 <body>                                  
  <form action="fav.php" method="post">                                                
   <b>Please enter your first name:</b>           
   <input type="text" size="45" name="username">  <br>
   <b>Please select your favorite color wine:</b> <br>             
   <input type="radio" name="color" value="white">  White           
   <input type="radio" name="color" value="ros">   Ros
   <input type="radio" name="color" value="red">    Red <br>
   <b>Please enter your favorite dish:</b>           
   <input type="text" size="45" name="dish"><br><br>
   <input type="submit" value="Submit This Form">
 </form>            
 </body>
</html>

在表单中,如果多个radio的name值相同,我们视为这些radio为一组单选按钮。

从代码可以看出,该表单是以post方式提交的,并且该表单创建了一组radio单选按钮,他们的name属性值都为color。

php代码:

<?php
  $username = $_POST['username'];
  $color =    $_POST['color'];
  $dish =     $_POST['dish'];

  if( $username != null )
  {
    echo( "Thanks for your selection $username <hr>" );
  }

  if( ( $color != null ) && ( $dish != null ) )
  {
    $msg = "You really enjoy $dish <br>";
    $msg .= "- especially with a nice $color wine";
    echo( $msg );
  }
?>

因为表单是以post方式提交,所以,在获取radio单选按钮的值时,使用了$_POST['color']。