How can CSS formatting be dynamically applied to form inputs based on PHP validation results?

To dynamically apply CSS formatting to form inputs based on PHP validation results, you can use PHP to add a specific class to the input elements depending on whether they pass or fail validation. Then, in your CSS, you can define styles for these classes to visually indicate the validation status to the user.

<?php
// PHP validation logic
$error = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form inputs
    if (empty($_POST["username"])) {
        $error = true;
    }
}

// Apply CSS class based on validation result
$inputClass = ($error) ? "error" : "success";
?>

<!DOCTYPE html>
<html>
<head>
    <style>
        .error {
            border: 1px solid red;
        }

        .success {
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <form method="post">
        <input type="text" name="username" class="<?php echo $inputClass; ?>" placeholder="Username">
        <input type="submit" value="Submit">
    </form>
</body>
</html>