How can form validation errors be displayed on the same page in PHP without redirecting?
When form validation errors occur in PHP, instead of redirecting to a new page, you can display the errors on the same page where the form is located. This can be achieved by using PHP to check for validation errors and then echoing out error messages directly in the HTML form. By doing this, the user can see the errors without being redirected, allowing them to correct the mistakes easily.
<?php
$errors = [];
// Check form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate form data
if (empty($_POST["username"])) {
$errors[] = "Username is required";
}
if (empty($_POST["password"])) {
$errors[] = "Password is required";
}
// If no errors, process form data
if (empty($errors)) {
// Process form data
}
}
// Display form with errors
?>
<form method="post" action="">
<?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>