如果下拉列表是在PHP代码中,如何在下拉列表中选择年份?

时间:2016-09-01 10:46:19

标签: php html

HTML:

<select class="col-lg-4 col-xs-12 col-sm-5" name="fromYear" ><?php $starting_year  =date('Y', strtotime('-50 year'));$ending_year = date('Y', strtotime('+4 year'));$current_year = date('Y');$selected_year = date('y',$profile->fromYear);for($starting_year; $starting_year <= $ending_year; $starting_year++) { echo '<option value="'.$starting_year.'"';if( $selected_year ) {echo ' selected="selected"'; }echo ' >'.$starting_year.'</option>';}?><select>

此代码动态生成Dropdown for Year。如何从此代码中的数据库中选择年份?例如,如果我在数据库中选择2009而不是此代码显示2009选择

2 个答案:

答案 0 :(得分:0)

我想你想把所选年份作为当年,请查看我的代码

    <select class="col-lg-4 col-xs-12 col-sm-5" name="fromYear" >
    <?php 
    $starting_year  =date('Y', strtotime('-50 year'));
    $ending_year = date('Y', strtotime('+4 year'));
    $current_year = date('Y');
    $selected_year = date('Y',$profile->fromYear);
    for($starting_year; $starting_year <= $ending_year; $starting_year++)
    { 
        echo '<option value="'.$starting_year.'"';
        if( $selected_year == $starting_year)
        {
            echo ' selected="selected"';
        }
        echo ' >'.$starting_year.'</option>';   
    }
    ?>
    <select>

答案 1 :(得分:0)

您不需要执行&#34; $ selected_year = date(&#39; Y&#39;,$ profile-&gt; fromYear); &#34;请检查我的代码

<?php
$starting_year = date('Y', strtotime('-50 year'));
$ending_year   = date('Y', strtotime('+4 year'));
$current_year  = date('Y');
$selected_year = $profile->fromYear; //previosly selected year
?>
<select class="col-lg-4 col-xs-12 col-sm-5" name="fromYear" >
<?php
  for($starting_year; $starting_year <= $ending_year; $starting_year++) {
     echo '<option value="'.$starting_year.'"';
     if($selected_year == $starting_year){
        echo ' selected="selected"';
     }
      echo ' >'.$starting_year.'</option>';
}?>