-1

我想读取用户在表单中选择的值,通过数据库填充。我累了,但发现只有静态填充的主题。另外,当动态填充列表时,如何设置默认选择?

<form enctype='multipart/form-data' action='' method='POST'>
//Other options to enter

<select name="crit">
$sql= "select Criteria from criterias";
$result= mysql_query($sql);
while ($row = mysql_fetch_array($result)){
echo "<option value=\"owner1\">" . $row['Criteria'] . "</option>";
}
?>
</select>
<input type="submit" name="Sub" value="Submit">
</form>


$POST['crit']; //dosen't work

还有owner1标签的用途是什么?我从网上拿了那块,它就像我想要的那样填充。

4

2 回答 2

0

检查它是否是第一行并设置选定的属性

<form enctype='multipart/form-data' action='' method='POST'>
//Other options to enter

<select name="crit">
$sql= "select Criteria from criterias";
$result= mysql_query($sql);
$count = 0;

while ($row = mysql_fetch_array($result)){
echo "<option " . ($count++ == 0 ? "selected=\"selected\"" : "") . " value=\"owner1\">" . $row['Criteria'] . "</option>";
}

// Access with 
$_POST["crit"]
于 2013-07-24T23:02:04.850 回答
0

不确定您要做什么,因为您选项中的值将全部为owner1。但是您可以在 while 循环中添加一个条件以默认选择一个选项。

//set any id in your url, this way we can match anything in your db with $GET['id']
if ($row['Criteria'] == $_GET['id']) 
{
    echo "<option value=\"owner1\" selected>" . $row['Criteria'] . "</option>";
}
else
{
     echo "<option value=\"owner1\">" . $row['Criteria'] . "</option>";
}

但如果您想自动选择第一个选项,请执行此操作。

$i = 0;
$selected= '';
while ($row = mysql_fetch_array($result))
{
     if ($i == 0) $selected = 'selected'; 
     echo "<option value=\"owner1\" ".$selected.">" . $row['Criteria'] . "</option>";
    else 
     $i++;
}
于 2013-07-24T23:02:39.263 回答