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.

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

Setup

The Radio Button Demo

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.
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.
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.