Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 提交后选择的下拉列表,但为今年首次_Php_Html_Forms_Dropdown_Selected - Fatal编程技术网

Php 提交后选择的下拉列表,但为今年首次

Php 提交后选择的下拉列表,但为今年首次,php,html,forms,dropdown,selected,Php,Html,Forms,Dropdown,Selected,我有个问题。我想用PHP创建一个下拉菜单,显示currentYear-2和currentYear+2。我创建了下拉菜单,但是在选择并提交了年份之后。它从未提交的年份重新开始 如果页面正在加载,则下拉列表从当前年份开始,然后在更改并提交所选年份后开始 非常感谢 获取和设置年份的PHP函数: function getCurrentYears(){ $thisYear = date("Y"); for($i=($thisYear-2); $i<($thisYear+3); $i

我有个问题。我想用PHP创建一个下拉菜单,显示currentYear-2和currentYear+2。我创建了下拉菜单,但是在选择并提交了年份之后。它从未提交的年份重新开始

如果页面正在加载,则下拉列表从当前年份开始,然后在更改并提交所选年份后开始

非常感谢

获取和设置年份的PHP函数:

function getCurrentYears(){
    $thisYear = date("Y");

    for($i=($thisYear-2); $i<($thisYear+3); $i++){
        echo "<option value='" .$i. "'>" .$i. "</option>";
    }
}
函数getCurrentYears(){ $thisYear=日期(“Y”); 对于($i=($thiswear-2);$i
$selected=($i==$row1['year']?'selected':'');
回显“$i”;

而$row1['year']是数据库中的值。这仅在您在数据库中提交年份时有效。

您可以在
选项中使用
selected
selected=“selected”

函数getCurrentYears(){ $thisYear=日期(“Y”)


for($i=($thiswear-2);$i您没有将
selected
键添加到
select
输入中。 另外,我建议您不要将视图与PHP代码混合使用



谢谢,伙计,但是现在如果我更改年份并提交它,例如2018年,那么下拉列表仍然是2020年,但我需要2018年。@SHbnkr所以在会话中存储用户第一次进来时,将从今年选择的内容添加到会话中。提交后添加提交到会话中。然后在会话中根据年份进行测试:
if($i==$\u会话['year']){$selected='selected';}
您好,谢谢您的提示。但是我如何使用$\u会话实现它?请查看dupe并从下面的答案中添加代码,您的意思是什么?^^它们中的任何一个都是真的。
https://stackoverflow.com/a/61520030/295783
<div>
<label for="chooseYear"> Choose a year </label>
     <select name="chooseYear" id="chooseYear" class="form-control">
       <option value='-'>-</option>
       <?php getCurrentYears(); ?>
    </select>
</div>
  $selected = ( $i == $row1['year'] ? ' selected' : '' );
   echo "<option value ='".$i."'".$selected.">".$i."</option>" ;
  for($i=($thisYear-2); $i<($thisYear+3); $i++){
        if($i == $thisYear){
            echo "<option value='" .$i. "' selected>" .$i. "</option>";
        }
        else{
             echo "<option value='" .$i. "' >" .$i. "</option>";
        }
    }
    }
<div>
    <label for="chooseYear"> Choose a year </label>
    <select name="chooseYear" id="chooseYear" class="form-control">
        <?php foreach (getYearsFromRange(range(date('Y') - 2, date('Y') + 3))
            as ['year' => $year, 'selected' => $selected]
        ): ?>
            <option value="<?php echo $year;?><?php echo ($selected) ? ' selected' : '';?>>
                <?php echo $year; ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>