Introduction

In the previous article you saw how to insert a value from a textbox into a MySQL database in PHP. In this article you will see how to insert a value from a radio button into a MySQL database using PHP.
First of all, we will create a database and table. The code for creating the database and table are as follows:
Create Database
  1. <?php
  2. $con = mysql_connect("localhost","root","");
  3. if (!$con)
  4. {
  5. die('Could not connect: ' . mysql_error());
  6. }
  7. if (mysql_query("CREATE DATABASE ABC",$con))
  8. {
  9. echo "Your Database created !!";
  10. }
  11. else
  12. {
  13. echo "Error creating database: " . mysql_error();
  14. }
  15. mysql_close($con);
  16. ?>
Create Table
  1. <?php
  2. $con = mysql_connect ("localhost","root","");
  3. if (!$con)
  4. {
  5. die ('Could not connect: ' . mysql_error());
  6. }
  7. mysql_select_db ("ABC", $con);
  8. $sql = "CREATE TABLE employee
  9. (
  10. name VARCHAR( 50 ) ,
  11. sex VARCHAR( 50 ) ,
  12. )";
  13. mysql_query($sql,$con);
  14. echo "Your Table Created !!";
  15. mysql_close($con);
  16. ?>
After creating the database and table, we will make a table. This table has two fields i.e. name and sex (male and female). Using this table we will insert data in the MySQL database.
Code
  1. <?php
  2. $con = mysql_connect("localhost","root","");
  3. mysql_select_db("ABC", $con);
  4. @$a=$_POST['name'];
  5. @$b=$_POST['sex'];
  6. if(@$_POST['submit'])
  7. {
  8. echo $s="insert into employee(name,sex) values('$a','$b')";
  9. echo "Your Data Inserted";
  10. mysql_query($s);
  11. }
  12. ?>
  13. <html>
  14. <body bgcolor="pink">
  15. <center>
  16. <form method="post">
  17. <table border="1" bgcolor="#00CCFF">
  18. <tr><td>Name</td>
  19. <td><input type="text" name="name"/></td>
  20. </tr>
  21. <tr><td rowspan="2">Sex</td>
  22. <td><input type="radio" name="sex" value="Male"/>Male</td>
  23. <tr>
  24. <td><input type="radio" name="sex" value="Female"/>Female</td></tr>
  25. </tr>
  26. <tr><td><input type="submit" name="submit" value="Submit"/></td></tr>
  27. </table>
  28. </form>
  29. </center>
  30. </body>
  31. </html>
Output
1st.gif
2nd.gif
3rd.gif
When you click on the submit button then the value of the name and sex fields will be in the MySQL database. As in the following image.
4th.gif

Conclusion

So in this article, you saw how to insert a value from a radio button into a MySQL database using PHP. Using this article one can easily understand the use of radio buttons in PHP.
Some Helpful Resources