Select box: how to populate years php

2019-06-24 19:32发布

i'm trying to populate a select box in php for years in a birthday field. A variable $year is set from a query and that particular year has to be selected in my select box. The code so far is this, it just populates the years but it doesn't select the year that is stored in mysql db, does anyone knows why? Thanks

$year = $row['year']; // this comes from a query that is stored in the db
<select name="year"><?
    for ($x = 1920; $x < date('Y'); $x++) {
    ?><option value=<? echo $x; if ($x == $year) {echo 'selected="selected"';}?>><? echo $x;?></option><?
}?>
</select>

2条回答
叛逆
2楼-- · 2019-06-24 20:02

Try this:

$year = (int)$row['year']; // this comes from a query that is stored in the db
?>
<select name="year"><?php
    for ($x = 1920; $x < date('Y'); $x++) {
?><option value="<?php echo $x . '"'; if ($x == $year) { echo ' selected="selected"';}?>><?php echo $x; ?></option><?
}?>
</select>

The main issue was you didn't close the value with double quotes, so the 'selected="selected" was included. so you got this:

<option value=1990selected="selected">1990</option>

Also, you didn't close the PHP tag before the <select

查看更多
Luminary・发光体
3楼-- · 2019-06-24 20:05

It looks like you've not left a gap between tags value and selected label. Try changing this:

<option value=<? echo $x; if ($x == $year) {echo 'selected="selected"';}?>><? echo $x;?></option>

to:

<option value="<? echo $x; ?>" <? if ($x == $year) {echo 'selected="selected"';}?>><? echo $x;?></option>
查看更多
登录 后发表回答