Skip to main content Jump to list of all articles

Getting to grips with PHP Radio Buttons

Following on from getting to grips with PHP Checkboxes I decided to write a little tutorial on radio buttons. As you know radio buttons can only have 1 state either on or off and only one can be selected at any one time. Here is a simple tutorial on how to get data from a database, select the radio button, get data from the form and update the database. If you have previously read and completed the setup procedure the process is the same so you may want to go straight to the code.  This script has now been included in wow playground with new and updated features.

Prerequisites

I am assuming that you have access to a PHP web server and have a MYSQL database. I highly recommend Xampp for your testing needs. I am also assuming that you know the basics on uploading and using an FTP program and have the use of a text editor or IDE.

Database Setup

When it comes to the database I like the simpler things in life so I use a MYSQL class from Ricocheting.com. This will be included within the script in which you can download from the bottom of this post. Unzip the download file and upload it to your server. As you can see the checkbox_demo folder has 1 file and 1 folder containing 3 files. Inside the lib folder there is the Database.class.php, config.php and setup.php and in the root folder there is index.php. First and foremost you need to open config.php and put your database settings in the appropriate places and save.

<?php
//database server
define('DB_SERVER', "");
 
//database login name
define('DB_USER', "");
//database login password
define('DB_PASS', "");
 
//database name
define('DB_DATABASE', "");
 
//smart to define your table names also
//define('TABLE_USERS', "");
//define('TABLE_NEWS', "");
?>

Now navigate to lib/setup.php with your browser. Below is the source of the setup file to give you an understanding.

Setup

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Database Setup</title>
</head>
<body>
	<h1>Setup</h1>
			<?php if (!isset($_POST['submit'])) { ?>
					<form name="setup" action="<?php $_SERVER['PHP_SELF']?>" method="post">
    					<input type="submit" value="Setup" name="submit" />
					</form>
<?php 			} 
					else
    				{
						require ('Database.class.php');
						$db->connect();
						$query= "CREATE TABLE IF NOT EXISTS options(
						id int(1) NOT NULL auto_increment,
						radio varchar (20) NOT NULL,
						primary key (id))";
						$db->query($query);

						$data['id'] = '';
						$data['radio'] = 'cat';
						$success=$db->query_insert("options",$data);
						
						if ($success)
							{
    							header('Location: ../index.php');
							}
    				}?>
</body>
</html>

The Radio Button Demo

      <?php  include('lib/Database.class.php');
                $db->connect();
                $query = "SELECT radio from options WHERE id='1'";
                $result = $db->query_first($query);
                $radio = $result['radio'];

                if ($radio == 'cat')
                        {$pet1 = 'checked="checked"';}
                            else {$pet1='';}
                if ($radio == 'dog')
                        {$pet2 = 'checked="checked"';}
                            else {$pet2='';}
                if ($radio == 'bird')
                        {$pet3 = 'checked="checked"';}
                            else {$pet3='';}
                if ($radio == 'rabbit')
                        {$pet4 = 'checked="checked"';}
                            else {$pet4='';}
                if ($radio == 'horse')
                        {$pet5 = 'checked="checked"';}
                             else {$pet5='';}
?>

Now as for index.php which I have split into 3 parts. The opening lines connect, query and get the value of the radio button from the database. It stores the value of radio to the variable $radio and then it checks to see which radio button value it matches and appropriately selects it.

      <?php     if (isset ($_POST['submitted']))
            {
                 $selected_radio='';
                   if       ($selected_radio == 'cat') {
                                 $pet1 = 'checked="checked"';}
                   else if ($selected_radio == 'dog'){
                                 $pet2 = 'checked="checked"';}
                   else if ($selected_radio == 'bird'){
                                 $pet3 = 'checked="checked"';}
                   else if ($selected_radio == 'rabbit'){
                                 $pet4 = 'checked="checked"';}
                   else if ($selected_radio == 'horse'){
                                 $pet5 = 'checked="checked"';}
                                 
                 $selected_radio=$_POST['pets'];
                 $data['radio']= $selected_radio;
                 $db->query_update("options",$data, "id='1'");
                 $db->close();
                 header('Location: index.php');
           }?>

The second part deals with the saving the data to the database. First it checks to see if the hidden field has been submitted then the variable $selected_radio is assigned the value of the radio button that has been selected and then the database is updated accordingly with the correct values and the page is told to refresh.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Simple Radio Button Test</title>
    </head>
    <body>
        <form action="<?php $_SERVER['PHP_SELF']?>" method="post">
                    <label title="Pets" for="pets" accesskey="p">Which one of the following is your favourite pet?</label><br/>
                    <input type="radio" name="pets" id="pet1" value="cat" <?php print $pet1 ?> />Cat<br/>
                    <input type="radio" name="pets" id="pet2" value="dog" <?php print $pet2?> />Dog<br/>
                    <input type="radio" name="pets" id="pet3" value="bird" <?php print $pet3?>  />Bird<br/>
                    <input type="radio" name="pets" id="pet4" value="rabbit" <?php print $pet4?>  />Rabbit<br/>
                    <input type="radio" name="pets" id="pet5" value="horse" <?php print $pet5?>  />Horse<br/><br/>
                    <input type="hidden" name="submitted" value="true" />
                    <input type="submit" value="ok" name="ok" />
        </form>
    </body>
</html>

As you can see in the 3rd part this is the basic form where the contents of the radio are determined by the values that have come from the database or have been changed by user input.

Download


Discover more from WorldOWeb

Subscribe to get the latest posts sent to your email.

2 replies on “Getting to grips with PHP Radio Buttons”

Comments are closed.