Liam Delahunty: Home Tips Web Contact
Recommended laptop
under £500
.

Think I deserve a present? See my Amazon Wish List

PHP Form Select Option pre-checked.

Select boxs and options are a great method of limiting the input from a user on a form to valid data only. However to maintain usability with the interface you really should pre-select the existing value.

print("<form action=\"$PHP_SELF\" method=\"post\">");
print("<select name=\"this_select_field\">");
$query = "SELECT id, field TABLES FROM table_name ";
$result = mysql_query($query, $connection);
while ($myrow = mysql_fetch_row($result)){
     print("<option value=\"$myrow[0]\"");
     if ($myrow[0] == $this_select_field) { print("selected"); }
     print(">$myrow[1]");
}
print ("</select>");
print ("<input type=\"Submit\" name=\"submit\" value=\"Submit\">");
print ("</form>");

Building a select box from an array can be very useful to:

Lets build an array, the key is a certain value corresponding to a users experience.

$user_lvl_array[1] = "Novice";
$user_lvl_array[100] = "User";
$user_lvl_array[200] = "Expert";
$user_lvl_array[300] = "Guru";

 
print ("<form action=\"\$PHP_SELF\"> method=\"post\">");
print ("<select name=\"new_user_level\">");
foreach ($user_lvl_array AS $key => $value){
     print("<option value=\"$key\"");
     if ($key == $new_user_level) { print("selected"); }
     print(">$value ($key)");
}
print ("</select>");
print ("<input type=\"Submit\" name=\"submit\" value=\"Submit\">");
print ("</form>");

Try it here


$new_user_level
$user_lvl_array[$new_user_level] .

Share this!