Save Radio Button Value Using PHP/MySQL

This Tutorial will teach you on how to save radio button value using PHP and MySQL. To start this tutorial let's follow the steps below.

Creating Our Database

First we are going to create our database which stores our data. To create a database: 1. Open PHPMyAdmin. 2. Click Databases. 3. In the "Create new database" box, type "radio". 4. The click Create button 5. Click SQL tab and paste the following code.
  1. CREATE TABLE IF NOT EXISTS `gender` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `gender` varchar(10) NOT NULL,
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

Creating Our Form

Next step is to create a form and save it as index.php. To create a form, open your HTML code editor and paste the code below after body tag.
  1. <?php $gender=$_GET['gender']; ?>
  2. <form action="save.php" method="post">
  3. Select Gender:<br />
  4. <label>
  5. <?php
  6. if ($gender=='male')
  7. {
  8. echo '<input name="gender" type="radio" value="male" checked="checked" />';
  9. }
  10. if ($gender=='female')
  11. {
  12. echo '<input name="gender" type="radio" value="male" />';
  13. }
  14. ?>
  15. male
  16. </label>
  17. <br />
  18. <label>
  19. <?php
  20. if ($gender=='female')
  21. {
  22. echo '<input name="gender" type="radio" value="female" checked="checked" />';
  23. }
  24. if ($gender=='male')
  25. {
  26. echo '<input name="gender" type="radio" value="female" />';
  27. }
  28. ?>
  29. female
  30. </label><br />
  31. <input name="Save" type="submit" value="save" />
  32. </form>

Creating our Connection

Next step is to create a database connection and save it as "connection.php". This file is used to connect our form to our database.
  1. <?php
  2. $mysql_hostname = "localhost";
  3. $mysql_user = "root";
  4. $mysql_password = "";
  5. $mysql_database = "radio";
  6. $prefix = "";
  7. $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
  8. mysql_select_db($mysql_database, $bd) or die("Could not select database");
  9. ?>

Writing Our Save Script

Next step is to create our save script and save it as save.php. This code is used to save the input data to our database.
  1. <?php
  2. include('connection.php');
  3. $gender=$_POST['gender'];
  4. mysql_query("INSERT INTO gender(gender)VALUES('$gender')");
  5. header("location: index.php?gender=$gender");
  6. ?>
That's it, you've been successfully created your code on how to save radio button value using php. Hope this code will help you, see you guys in my next tutorial.

Comments

Submitted byAnonymous (not verified)on Tue, 02/05/2013 - 20:35

This is a great tutoral

Add new comment