Jump to content

Drop menu using session data


parka

Recommended Posts

I've a drop menu for users to choose the month they are born from.

There's an associative array, $nameOfMonths, for the months' names. E.g. [1] => 'January', $birthMonth would be an Int

 

If there's session data, it will print the user selected month, followed by a list of months.

If there's no session data, it will ask user to select a month, followed by a list of months.

 

I wonder if this is the best way to code this drop menu.

 

<select name="birthmonth" id="birthmonth" value="Select">
<?php
// There's input in session data
if ($birthMonth != 'selectdob'){
print "<option value=\"$birthMonth\" selected=\"selected\">{$nameOfMonths["$birthMonth"]}</option>";
foreach ($nameOfMonths as $intMonth => $months){
	print "<option value='$intMonth'>$months</option>\n";
}
} else { // What users see on first load, with NO session data
print "<option value=\"selectdob\" selected=\"selected\">Select a month</option>";
foreach ($nameOfMonths as $intMonth => $months){
	print "<option value='$intMonth'>$months</option>\n";
}
}
?>	
</select>

Link to comment
https://forums.phpfreaks.com/topic/41103-drop-menu-using-session-data/
Share on other sites

What i would be tempted to do is see if the session has been set.

 

for example using isset()

 

In your case what i would do is this:

 

<select name="birthmonth" id="birthmonth" value="Select">
<?php
// There's input in session data
if ($birthMonth != 'selectdob'){
print "<option value=\"$birthMonth\" selected=\"selected\">{$nameOfMonths["$birthMonth"]}</option>";
foreach ($nameOfMonths as $intMonth => $months){
	print "<option value='$intMonth'>$months</option>\n";
}
} 
else if (!isset($_SESSION['varable_name'])) //notice i am checking to see if the varable is set.
{ // What users see on first load, with NO session data
print "<option value=\"selectdob\" selected=\"selected\">Select a month</option>";
foreach ($nameOfMonths as $intMonth => $months){
	print "<option value='$intMonth'>$months</option>\n";
}
}
?>	
</select>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.