查询Mysql和Echoing下拉选择

时间:2014-05-01 15:50:04

标签: php mysql dropdownbox

我已经构建了一个包含文本字段,文本区域,单选按钮和下拉列表的表单,并且我已经创建了一个查询来从适当的行从数据库中提取数据,但是不能弄清楚如何编程下拉以反映mysql行中的选择。以下是我能够正确编程的字段示例:

<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>

这些都可以正确地从mysql数据库中提取数据,但是我试图弄清楚如何对下拉菜单进行编程,以便在拉出此表单时,选择会填充/显示所选的值。形式拉了:

<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>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您需要将“已选择”附加到您想要在下拉列表中预先选择的选项。

<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>

答案 1 :(得分:-1)

试试这个例子:

 //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>";
}