[英]How to set the default value in a dynamic drop down
我有一個從MySQL database
動態填充的drop down select
,我需要默認下拉值以根據用戶選擇的記錄顯示。 到目前為止,我沒有在下拉列表中顯示任何值。 但是我的代碼在select選項語句之外,並且以粗體顯示默認值。 我似乎無法理解if語句邏輯。
用戶從數據表中選擇一條記錄,然后單擊“編輯”。 例如,用戶選擇了以灰色突出顯示的行,然后單擊“ edit”(將其發送到編輯表單)
編輯表單:我將單位ID傳遞給編輯表單,並根據傳遞的ID預填充輸入字段,但是在這里我無法填充並設置默認的下拉選項值
這是下拉選擇(div id下拉)的編輯表單后面的代碼
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','*********');
define('DBNAME','fdmamaint');
if (!$db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME)) die("Can't connect to database");
// Retrieve the record the user selected
$id = htmlspecialchars($_GET["id"]);
// Query the depunits table based on the user selection
$sql = "SELECT unit_id, div_id, title_org, short_desc, long_desc, unit_desc, avail_ind "
. "FROM depunits "
. "WHERE unit_id=$id";
if (!$result = $db->query($sql)){
die("There was an error running the query [" .$db->error. "]");
}
// Walk through the result set and assign variables for reference later on in the script
while ($row = $result->fetch_assoc()){
$unitId = $row['unit_id'];
$divId = $row['div_id'];
$titleOrg = $row['title_org'];
$shortDesc = $row['short_desc'];
$unitDesc = $row['unit_desc'];
$longDesc = $row['long_desc'];
$enabled = $row['avail_ind'];
}
// Div Id - query database to get drop down select options
$divSelect = "SELECT div_id, long_desc FROM depdivisions "
. " WHERE div_id <> '' and avail_ind='Y' and active_ind='Y'"
. " ORDER BY div_id";
if (!$divResult = $db->query($divSelect)){
die("There was an error running the query [" .$db->error. "]");
}
.......
動態下拉選擇:
<!-- Div Id -->
<label for="divId" class="control-label">Div Id</label>
<select class="form-control" name="divId" id="divId">
<option value=" "></option>
<?php
while ($rowDivs = $divResult->fetch_assoc())
{
$data = '37' .$rowDivs['div_id'];
// if the value of $data matches the value of div id of the
// user selected row in the database then give that option
// value the selected tag
if ( $data == $divId)
{
echo "<option value=". $data ."selected>";
echo $data ;
echo "</option>";
}
else
{
echo "<option value=". $data .">";
echo $data;
echo "</option>";
}
}
我可以在while語句中有if / else語句嗎? 這也許就是為什么我沒有在下拉菜單中得到任何數據結果的原因嗎?
我想到了:
我需要使用內聯if語句,如下所示:
<!-- Div Id -->
<label for="divId" class="control-label">Div Id</label>
<select class="form-control" name="divId" id="divId">
<option value=" "></option>
<?php
while ($rowDivs = $divResult->fetch_assoc()) {
$data = '37' .$rowDivs['div_id'];
echo "<option value=$data" .($data == $divId ? ' selected="selected"' : '') . ">$data</option>";
}
?>
</select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.