How can missing fields be displayed after submission in a PHP form with radio buttons?
When a form with radio buttons is submitted in PHP and there are missing fields, the missing fields can be displayed by storing the user's input in session variables and then checking and displaying them after submission. To achieve this, you can check if the required fields are empty and store the user input in session variables. After submission, you can display the missing fields by checking the session variables and highlighting the missing fields in the form.
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$_SESSION['name'] = $_POST['name'];
$_SESSION['gender'] = $_POST['gender'];
if(empty($_POST['name'])){
$error_name = "Name is required";
}
if(empty($_POST['gender'])){
$error_gender = "Gender is required";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : ''; ?>"><br>
<span style="color: red;"><?php echo isset($error_name) ? $error_name : ''; ?></span><br>
Gender:
<input type="radio" name="gender" value="male" <?php if(isset($_SESSION['gender']) && $_SESSION['gender'] == 'male') echo 'checked'; ?>> Male
<input type="radio" name="gender" value="female" <?php if(isset($_SESSION['gender']) && $_SESSION['gender'] == 'female') echo 'checked'; ?>> Female
<span style="color: red;"><?php echo isset($error_gender) ? $error_gender : ''; ?></span><br>
<input type="submit" value="Submit">
</form>
Related Questions
- How can the use of absolute URIs with schemas and hostnames impact URL redirection in PHP?
- Is storing page content in a database and retrieving it using a function a more efficient method than using Switch Case for page linking?
- How can a beginner in PHP ensure secure database interactions, especially when retrieving data from a MySQL database?