我想用php / mysql查询给下拉列表一个默认值
在db表用户中有一条记录说usergroup
我想要它所以下拉默认值更改为该记录的值到目前为止我得到此代码:
Usergroup: <select value=\"" . $usergroup . "\" name='usergroup'>
<option value='4'>Administrator</option>
<option value='3'>Moderator</option>
<option value='2'>Donator</option>
<option value='1'>Regular Member</option>
</select>
和php部分:
$username = mysql_real_escape_string(htmlentities(stripslashes($_POST['username'])));
$query="SELECT * FROM users where `username` like '{$username}'";
$result = mysql_query($query);
$num = mysql_numrows($result);
$i=0;
while ($i < $num) {
$username2=mysql_result($result,$i,"username");
$name=mysql_result($result,$i,"name");
$usergroup=mysql_result($result,$i,"usergroup");
$email=mysql_result($result,$i,"email");
$ip=mysql_result($result,$i,"ip");
$profpic=mysql_result($result,$i,"profilepic");
$id=mysql_result($result,$i,"id");
$i++;
}
谢谢你!
我让它与一些if语句一起使用,我打算以这种方式使用它,但不希望代码变得太乱:
if ($usergroup == 4) {
echo "<select name='usergroup'><option value='4' selected='selected'>Administrator</option><option value='3'>Moderator</option><option value='2'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 3) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3' selected='selected'>Moderator</option><option value='2'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 2) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3'>Moderator</option><option value='2' selected='selected'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 1) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3'>Moderator</option><option value='2'>Donator</option><option value='1' selected='selected'>Regulat Member</option></select><br>";
}
答案 0 :(得分:2)
这可能就是你要找的东西:
<?php
// $userGroup = the value from the database
$userGroup = 4;
?>
<select>
<option <?php echo ($userGroup) == 1 ? "selected" : "" ?> value="1">Administrator</option>
<option <?php echo ($userGroup) == 2 ? "selected" : "" ?> value="2">Moderator</option>
<option <?php echo ($userGroup) == 3 ? "selected" : "" ?> value="3">Donator</option>
<option <?php echo ($userGroup) == 4 ? "selected" : "" ?> value="4">Regular member</option>
</select>
如果您不识别if / else语法(简写),check out this guide。对于这样的情况真的很方便。