How do I check if one of two radio buttons is checked with PHP?
HTML
<form action="" method="post">
<b>Yes or No?</b><br>
Yes <input type="radio" name="template" value="Yes">
NO <input type="radio" name="template" value="No"><br><br>
<input type="submit" name="send" value="Skicka internlogg">
</form>
I don't want one of this two radio buttons to be checked from the beginning. I want an if-statement that continue with the code if one of them are checked by the user. And if not I want to print an error code like "Please fill the whole form" or something. How?
I then want to check for multiple statements from radio buttons and text boxes, how?
if($_POST['sr'] && $_POST['relevant'] && if(isset($_POST['article'])) && if(isset($_POST['template'])) && $_POST['text']) {} ?????
Upon form submission, check to see if the POST variable "template" is not set using isset.
The ! in front of isset means "not". Therefore, it is checking to see if "template" is not set.
You should check each element of your form separately so you can provide constructive feedback to the end-user on what they need to do to resolve the error message. This is considered best practice and something you should do on any form, regardless how big or small.
<?php
// Form submitted
if(isset($_POST['send'])) {
// CHECK FOR ERRORS
// Check for radio button value
if(!isset($_POST['template'])) {
// No value for template, show error message
$e['template'] = "<p><strong>Please select Yes or No.</strong></p>";
}
// Check the value of text box
if(!isset($_POST['relevant'])) {
$e['relevant'] = "<p><strong>Please fill out the Relevant field.</strong></p>";
}
// If no errors occurred, finish processing the form
if(!is_array($e)) {
// Do stuff (db update, email send out, etc.)
// Show thank you message
echo "<p>Thank you. We have received your submission.</p>";
exit();
}
}
?>
<form action="" method="post">
<?php echo $e['relevant']; ?>
<p><label for="relevant">Relevant:</label><input type="text" name="relevant" id="relevant" value="<?php echo htmlspecialchars($_POST['relevant']); ?>" /></p>
<?php echo $e['template']; ?>
<p>Yes or No?</p>
<p><label for="yes">Yes</label><input type="radio" name="template" id="yes" value="Yes" <?php if($_POST['template'] == "Yes") { echo 'checked="checked"'; } ?> /></p>
<p><label for="no">No</label><input type="radio" name="template" id="no" value="No" <?php if($_POST['template'] == "No") { echo 'checked="checked"'; } ?> /></p>
<p><input type="submit" name="send" value="Skicka internlogg" /></p>
</form>
EDIT: To address you wanting to do the check all at once, which you should not get in the habit of doing, you could do something like this:
if(!isset($_POST['template']) || !isset($_POST['relevant']) || !isset($_POST['sr']) || ... ) {
$error = "<p>Please fill out all form fields.</p>";
}
Then echo the error out in the form as in my example above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With