How can PHP be used to validate form input and display error messages?
To validate form input and display error messages in PHP, you can use conditional statements to check the input data and display error messages if the data does not meet the required criteria. You can also use PHP functions like isset() and empty() to ensure that the form fields are filled out before processing the data.
<?php
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$error = "Username is required";
} else {
// Process the form data
$username = $_POST["username"];
// Additional validation and processing
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="text" name="username">
<span style="color: red;"><?php echo $error; ?></span>
<input type="submit" value="Submit">
</form>