How can PHP variables be used to display error messages in HTML for incorrect user input?
To display error messages in HTML for incorrect user input using PHP variables, you can set an error message in a PHP variable when validation fails, and then display it in the HTML code where appropriate. This can be achieved by using conditional statements to check for errors and output the error message within the HTML markup.
<?php
$error = "";
// Validate user input
if(empty($_POST['username'])) {
$error = "Username is required.";
}
// Display error message in HTML
if(!empty($error)) {
echo '<div class="error">' . $error . '</div>';
}
?>
<form method="post">
<input type="text" name="username" placeholder="Enter username">
<button type="submit">Submit</button>
</form>