There are certain situations that require the use of checkboxes. For example, you could have a checkbox for “I accept the terms and conditions” or “Keep me up to date with promotions”.
There are certain situations however, which would be better suited to a radio button. A radio button is just a checkbox in which only one value can be checked. For example, you might have a radio button for male or female. If the male button is checked, the female one becomes unchecked. In this tutorial I’ll show you how to use both.
Checkbox
Add your checkbox to your <form> block:
<form action="" method="post"> Do you accept the terms and conditions? <input type="checkbox" name="terms" value="Yes" /> <input type="submit" name="submit" value="Submit" /> </form>
And then your form handler:
<?php if (isset($_POST['submit'])) { if(isset($_POST['terms'])) { echo "Checkbox was checked!"; } else { echo "Checkbox was NOT checked!"; } } ?>
Radio buttons
Add the radio buttons to your <form> block:
<form action="" method="post"> <input type="radio" name="myRadio" value="male">Male <input type="radio" name="myRadio" value="female">Female <input type="submit" name="submit" value="Get Selected Values" /> </form>
And finally your php handler:
<?php if (isset($_POST['submit'])) { if(isset($_POST['myRadio'])) { echo "You have selected: " . $_POST['myRadio']; } } ?>
This will output “You have selected: male” or “You have selected: female”. Alternately, you could handle it by checking if they selected male or female:
<?php if (isset($_POST['submit'])) { //Check if the radio was set i.e. if any if the radios have been selected if(isset($_POST['myRadio'])) { if($_POST['myRadio'] == "male") { echo "You selected male"; } else { echo "You selected female"; } } } ?>
You can use this value in your MySQL queries just like you would do with any other post variables:
$gender = $_POST['myRadio']; INSERT INTO users VALUES('$name', '$age', '$gender');
So that’s it really, both super easy to use! 🙂
Check out my facebook page for tutorials, tips and tricks!
Reece