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>
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
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>