1

我想使用 php / mysql 查询为下拉列表提供默认值

就像在 db 表 users 中有一条记录说 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>";
}
4

1 回答 1

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 语法(简写),请查看本指南。对于这种情况真的很方便。

于 2012-08-07T11:15:41.440 回答