设置默认下拉列表值

时间:2012-07-09 04:02:25

标签: php forms

我有一个向我的数据库提交2个值的表单,当表单加载时我检查数据库中是否已有值,我一直在尝试使用这些值并在我的下拉框中将它们设置为默认值。任何帮助,将不胜感激。感谢

<form method="post" action="add_res.php?id=<? echo $id;?>">
    <fieldset>
    <label>From</label>
    <select name='one' id='one'>
    <?
        for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
            for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
                echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';
    ?>
    </select><br><br>
    <select name='two' id='two'>
    <?
        for($hours=0; $hours<24; $hours++)
            for($mins=0; $mins<60; $mins+=30)
                echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'.str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';
    ?>
    </select>
    </fieldset>
    <input type="submit" value="Restrict" class="btn_searchp"></a>
</form>

1 个答案:

答案 0 :(得分:0)

您必须合并该值,然后与数据库值进行比较

<select name="one" id="one">
<?php for loop
$timeToDisplay = sprintf('%s:%s',str_pad($hours,2,'0',STR_PAD_LEFT),
                                 str_pad($mins,2,'0',STR_PAD_LEFT));
$selected = if($row['timeRow'] == $timeToDisplay ) ? 'selected="selected"' : '';
// let $row['timeRow'] is the value retrieve from database 
?>
   <option value="<?=php echo $timeToDisplay;?>" <?php echo $selected;?> >
     <?php echo $timeToDisplay?>
   </option>
</select>

参考文献:

sprintf

ternary operator