从数据库填充下拉列表并设置默认值 [英] Populate dropdown from database and set default value
问题描述
现在,我有一个可行的解决方案,可通过 PHP/MYSQLI 从我的database: listoption
的内容填充HTML <select>
/<option>
-下拉列表.
Right now I have a working solution for populating an HTML <select>
/<option>
-dropdown with the content through PHP/MYSQLI from my database: listoption
.
数据库:
DATABASE NAME:
# listoption
TABLES:
# ID INT(11) *Primary AI
# listoption_item VARCHAR(255)
这是其他代码(不是mysqli connect,而是之后的所有内容.)
Here's the other code (not the mysqli connect but everything afterwards..)
<?php
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
但是现在的问题是,我希望通过该查询填充的这些选项之一是selected
.并且要选择的选项应由URL中的参数确定,例如:index.php?id=1
.
因此,现在我需要以某种方式将IF/ELSE和$_GET['id'];
添加到代码中,以使其标识数据库中的ID是否与填充的项目相同,然后将其设置为selected.
But the problem is now that I want to have one of these options that are populated through that query to be selected
. And the option to be selected should be determed by a parameter in the URL, for example: index.php?id=1
.
So now I need to somehow add a IF/ELSE and a $_GET['id'];
into the code to make it identify if the ID from the database is the same as the populated item and then set it to selected.
有任何想法吗?谢谢!
推荐答案
您可以按照以下步骤进行操作:
You can do that like given below:
<?php
$result = $mysqli->query("select * from listoption");
$id = ($_GET['id'])? $_GET['id'] : '';
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
$sel = ($id == $row['id'])? 'selected="selected"':'';
echo '<option value="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>'; // $sel will deside when to set `selected`
}
echo "</select>";
?>
这篇关于从数据库填充下拉列表并设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!