Hi! I have three <select> elements that I use to enter data about day, month and year in a database. In a specific page of the site the user has the possibility to edit the date, and I would like the page to automatically select the correct elements of the menu based on the information in the database (so that, if the date inserted is 01-02-2011, the third <select> element would have the “2011” element already selected).
I was thinking about the following solution:
//
// retrieve information from the database and save it in the variables $day, $month and $year
//
if ($year == '2011') {
echo '<select>
<option value="2011" selected="selected">2011</option>
<option value="2012">2012</option>
</select>';
else if ($year == '2012') {
echo '<select>
<option value="2011">2011</option>
<option value="2012" selected="selected">2012</option>
</select>';
}
Centrex is pretty well on the money, but as NULL gets cast to an empty string when being used in building $options you might as well make it an empty string to begin with.
The ternary operator is also handy in this situation to have a more compact line.
Here is a function I found years ago and used for a long while. It goes to the db and gets elements for your droplist and matches to the one you want.
function ListboxMatch($size, $name, $query, $matchtothis) {
mysql_select_db($dbname,$mysql_link);
$qry = mysql_query($query,$mysql_link);
if (mysql_num_rows($qry) > 0)
{ echo "<SELECT SIZE='".$size."' NAME='".$name."'>" , PHP_EOL;
while (list($value, $text) = mysql_fetch_row($qry))
{ echo "\ <OPTION VALUE='".$value."'";
if ($value == $matchtothis)
{ echo " SELECTED"; }
echo ">".$text."</option>" . PHP_EOL;
} echo "</SELECT>" . PHP_EOL;
} else echo "No data in listbox" . PHP_EOL;
mysql_free_result($qry);
}
No guarantee all these mysql_* functions are correct or still exist - but might give you some ideas - it clearly needs some cleaning up (all caps for html elements, wtf?), but still it should work.
$this_person = 7; // from get or post or session etc
// get 2 things, the value and the text you want to display
$query = "select id, name from people order by name";
// it echoes everything to the screen when called, so put this
// line in the correct place
ListboxMatch(1, 'people', $query, $this_person);
I remember taking this idea and improving it somewhat but I cannot remember where the code is.