简体   繁体   English

PHP MySQL 下拉框填充选定值

[英]PHP MySQL Drop Down Box Populate Selected Value

I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one.我已阅读有关如何使用 MySQL 填充整个下拉列表的教程,但我遇到的问题是我只想从数据库中获取一个并将其作为选定的一个。 So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'.因此,我希望在数据库中有一个包含三个项目(Item1、Item2、Item3)的下拉列表,它存储在名为 itemschoice 的列中,其值为“Item2”。 How do I go about getting item2 to be selected when I load the drop down box?我如何在加载下拉框时选择 item2?

In your <option> element add the selected attribute for the value that is in itemschoice .在您的<option>元素中,为itemschoice中的值添加selected属性。

Crude example using a made up function to get the choice:使用编造的 function 获得选择的粗略示例:

$choice = get_items_choice();
$results = mysqli_query($sql);

echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
    if ($row['choice'] === $choice) {
        echo '<option value="' . $choice . '" selected="selected" />';
    } else {
        echo '<option value="' . $choice . '" />';
    }
}
echo '</select>';

This is just an example, don't copy & paste this without adding some kind of error verification!这只是一个示例,请勿在未添加某种错误验证的情况下复制和粘贴此内容!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM