Question

I have built a form that has text fields, text areas, radio buttons, and drop downs, and I've created a query to pull the data from the database at the appropriate row, but can't figure out how to program the drop down to reflect the choice that's in the mysql row. Here are a sample of the fields I've been able to program correctly:

<label for="contactname">Contact Name:</label>
<input type="text" name="contactname" value="<?php echo $query['contactname']; ?>"

<label for="delay">Delay:</label>
<input id="Yes"  type="radio" name="delay" value="Y" <?php if($query['delay']==='Y') echo 'checked'; ?> >Yes 
<input id="No" type="radio" name="delay" value="N" <?php if($query['delay']==='N') echo 'checked'; ?> >No

<label for="notes">Notes: </label>
<textarea name="notes" id="notes"><?php echo $query['notes']; ?></textarea>

These have all worked in pulling data from the mysql database correctly, but I'm trying to figure out how to program the drop downs so that when this form is pulled, the selection populates/displays the selected value when the form is pulled:

<label for="day">Select Option:</label>
<select name="day"> 
     <option value="0">Monday </option>
     <option value="1">Tuesday </option>
     <option value="2">Wednesday </option>
     <option value="3">Thursday </option>
     <option value="4">Friday </option>
</select>

Thanks for your help!

Était-ce utile?

La solution

You need to append " selected" to the option you want pre-selected in the dropdown.

<label for="day">Select Option:</label>
<select name="day"> 
 <option value="0"<?php if ($query['day'] == 0) echo ' selected="selected"'; ?>>Monday</option>
 <option value="1"<?php if ($query['day'] == 1) echo ' selected="selected"'; ?>>Tuesday</option>
 <option value="2"<?php if ($query['day'] == 2) echo ' selected="selected"'; ?>>Wednesday </option>
 <option value="3"<?php if ($query['day'] == 3) echo ' selected="selected"'; ?>>Thursday</option>
 <option value="4"<?php if ($query['day'] == 4) echo ' selected="selected"'; ?>>Friday</option>
</select>

Autres conseils

try this example:

 //array as an example
 $your_db_array = array ('value1','value2','value3');

 // Make the pull-down menu:
 echo '<select name="pull_down">';
 foreach ($your_db_array as $key => $value) {
echo "<option value=\"$key\"";
// Check for stickyness:
if (isset($value_from_DB['value']) && ($value_from_DB['value'] == $key) ){ 
       echo ' selected="selected"';}
echo ">$value</option></select>";
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top