开发者

Showing current value in DB in a drop down box

this is my code which populates a drop down menu, all working perfectly, but when editing a database record, i want the first value in the drop down to be what is currently in the database, how would i do this?

<li class="odd"><label class="field-title">Background <em>*</em>:</label> <label>开发者_C百科;<select class="txtbox-middle" name="background" />
                        <?php
                        $bgResult = mysql_query("SELECT * FROM `backgrounds`");
                        while($bgRow = mysql_fetch_array($bgResult)){
                            echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
                        }
                        ?>
                    </select></li>


You would set the selected="selected" attribute on the relevant <option>. Presumably there would be some sort of check in your while loop, checking against the variable that contains the current value.


You can do like:

$counter = 1;
while($bgRow = mysql_fetch_array($bgResult)){
  if ($counter === 1)
  {
    echo '<option value="'.$bgRow['name'].'" selected="selected">'.$bgRow['name'].'</option>';
  }
  else
  {
    echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
  }

  $counter++;
}

As can be seen I have added selected="selected" for you so it will work automatically for you :)


Correct me if I'm wrong, I believe that you have another database table which holds the selected background (e.g. users table with background field), you need to do a query to get the background from the other table and add selected="selected" attribute to the option tag of the background, please check the code below (hope it helps):

<?php
    $result = mysql_query("SELECT `background` FROM `users` LIMIT 1");
    $myBg   = mysql_fetch_array($result, MYSQL_ASSOC);      
    $bgResult = mysql_query("SELECT * FROM `backgrounds`");
    while($bgRow = mysql_fetch_array($bgResult)){
        if($myBg['background'] == $bgRow['name'])
            echo '<option value="'.$bgRow['name'].'" selected="selected">'.$bgRow['name'].'</option>';
        else
            echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
    }
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜