在php中提交后保留选择框数据

I want my select box to retain data after submitting a form. The following is the code.

  foreach ($data as $row) {

            $selected = '';

            if (isset($_SESSION['classes']) && !empty($_SESSION['classes'])) {
                global $selected;
                $sessions = $_SESSION['classes'];
                $cls_val = $row['id'];
                if ($sessions == $cls_val) {
                    $selected= "selected";
                    echo $selected;
                }
        }
            $html.= '<option $selected value="'.$row['id'].'">'.Purifier($cls_full_data).'</option>';
        }
    echo  '<select name="class_id" id="class_id" class="form-control form-control-sm font-label">'.$html.'</select>';
    echo '<br>';

the code does not have any problems with showing the dropdown, however, I can't get the selected values after submit.

This looks much better.

$html='';
$sessions='';
if (isset($_SESSION['classes']) && !empty($_SESSION['classes'])) {
    $sessions = $_SESSION['classes'];
}
foreach ($data as $row) {
    $selected = '';
    if ($sessions == $row['id']) {
        $selected= 'selected';
    }
    $html.= '<option value="'.$row['id'].'" '.$selected.'>'.Purifier($cls_full_data).'</option>';
}
echo '<select name="class_id" id="class_id" class="form-control form-control-sm font-label">'.$html.'</select>';
echo '<br>';

change your code to this:

foreach ($data as $row) {

        $selected = '';

        if (isset($_SESSION['classes']) && !empty($_SESSION['classes'])) {
            global $selected;
            $sessions = $_SESSION['classes'];
            $cls_val = $row['id'];
            if ($sessions == $cls_val) {
                $selected= "selected";
                echo $selected;
            }
    }
        $html.= '<option '.$selected.' value="'.$row['id'].'">'.Purifier($cls_full_data).'</option>';
    }
echo  '<select name="class_id" id="class_id" class="form-control form-control-sm font-label">'.$html.'</select>';
echo '<br>';