Selection box: how to fill in php years

I have been trying to fill in a select box in php for many years in a birthday box. The variable $ year is set from the request, and this particular year should be selected in my selection field. The code so far is that it just fills the years, but does not select the year that is stored in mysql db, does anyone know 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> 
+4
source share
2 answers

Try the following:

 $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 problem was that you did not close the value with double quotes, so 'selected="selected" was included. so you got this:

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

Also, you did not close the PHP tag before <select

+7
source

It looks like you did not leave a space between the tag value and the selected label. Try changing this:

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

in

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

Source: https://habr.com/ru/post/1397523/


All Articles