how do i stop the form input input data from erasing after php validation?

Instead of echoing the value into the input, you need to echo selected on the correct option. It should look something like this.

Also, valid HTML will only allow one option in a select to have the selected attribute. Your default option (<option disabled selected>Select Month</option>) might be causing a problem.

   <?php
if (!empty($_POST)) {
    $error = false;
    if (empty($_POST["expMonth"])) {
        echo "<p class='errorMessage'> Month must be selected. </p>";
        $error = true;
    }
    if (!$error) {
        header("Location: confirmation.php");
        exit;
    }
}
?>
<th><label for="expDate">Expiration Date</label></th>
<td><select id="expMonth" name="expMonth">
<?php
$months = [
    '1' => 'January',
    '2' => 'February',
    '3' => 'March',
    '4' => 'April',
    '5' => 'May',
    '6' => 'Jone',
];


foreach ($months as $key => $value) {
    $selected = '';
    if (isset($_POST["expMonth"]) && $_POST["expMonth"] == $key) {
        $selected = 'selected';
    }
    echo "<option value='{$key}' {$selected}>{$value}</option>";
}
?>
</select>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top