1

我有一个下拉菜单,用户可以从中选择一个位置。这些是保存的设置,所以如果用户想要编辑这些设置,我希望之前保存的值填充列表。

位置及其 ID 是从名为 locations 的表中选择的,但是,只有位置保存在名为 userinfo 的表中。考虑到第一次在选择过程中使用了 id,我不确定如何再次填充选择列表。

这就是我现在可以简单地选择一个地点。我想用以前保存的位置填写。这是较大表单的一部分,因此没有表单标签。

<?
$sql = mysql_query("select locationsid,locationsName from locations"); 
$selection="";
while ($row=mysql_fetch_array($sql)){ 
   $id=$row["locationsid"]; 
   $locationName = $row["locationsName"]; 
   $selection.="<OPTION VALUE=\"$id\">".$locationName; 
}
?>
<!--select location - used for reach location -->
<h4>Nearest Location</h4>
<table>
<tr><td>Location:</td><td><select name ="location"><Option value="<? echo selection2; ?>">Choose Location<? echo $selection; ?></Select></td>
</table>

我假设我必须查询数据库以获取保存的位置(在 userinfo 表中),然后从位置表中查找该位置的 ID。从这里开始,我不太确定如何将其填充到值选择字段中。

$locationLookup = mysql_query("select location from userinfo where userid = $userid");
$locationLookup = mysql_fetch_array($locationLookup);
$location = $locationLookup['location'];
$idlookup = mysql_query("select locationsID from locations where locationsName = '$location'");
$idlookup = mysql_fetch_array($locationid);
$idlookup = $locationid['locationsID'];

那么,这会给我名称和 ID,我如何将其设置为选择列表中的值?

4

1 回答 1

1

得到后$idlookup

$idlookup = $locationid['locationsID'];

while在循环内使用它:

while ($row=mysql_fetch_array($sql)){ 
   $id=$row["locationsid"]; 
   $locationName = $row["locationsName"]; 
   $selected = ($id == $idlookup) ? 'selected="selected"' : '';
   $selection.="<OPTION " . $selected . " VALUE=\"$id\">".$locationName."</OPTION>";
}
于 2012-05-30T02:18:02.357 回答