Skip to content
Advertisement

How to stop the form input type select data from erasing after PHP form validation?

I’m working on an e-commerce website, and I’m trying to validate a form using PHP. So with my current code, the data doesn’t get erased after I submit the form and if there is an error, all the data stays in the form and shows an error message, but I cannot make the same for the select options. What am I missing here?

<?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
      if (isset($_POST["expMonth"])) echo "value='" . $_POST["expMonth"] . "' selected";
    ?>>
     <option disabled selected>Select Month</option>
     <option value="1">January</option>
     <option value="2">February</option>
     <option value="3">March</option>
     <option value="4">April</option>
     <option value="5">May</option>
     <option value="6">Jone</option>
     </select>

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement