使用php mysql动态创建带有optgroup的选项列表

时间:2014-07-20 16:36:51

标签: php html mysql

我试图在HTML选项列表中创建成员列表,但我希望根据每个成员的部门进行划分,因为每个成员都在公司的某个部门工作。 这是我试图使用但不成功的代码:

    <?php
   echo'<select size=1 name="Name List">'."\n";
   echo'<option value="-1">--Name List--</option>'."\n";
   $result1=mysql_query("select department from users");

   while($data1=mysql_fetch_array($result1)){

   echo'<optgroup value="'.$data1[0].'">'.$data1['department'];

    $result=mysql_query('select username from users where department="'.$data1['department'].'" ');

   while($data=mysql_fetch_array($result)){

   echo'<option value="'.$data[0].'">'.$data['username'];
   echo'</option>'."\n";
   }
   echo'</optgroup>'."\n";
   }
   echo'</select>'."\n";
   mysql_close();
   ?>

1 个答案:

答案 0 :(得分:0)

首先,为成员提供一个单独的表,为部门提供另一个表。

每个表都有自己的id和其他字段。在这种情况下,你需要将members_id中的department_id作为外键。

部门表:

enter image description here

会员表:

enter image description here

所以在你的代码中接下来你应该加入这两个表来获取相关数据:

代码:

  <?php
  $con = mysql_connect("localhost","username","pass");
  mysql_select_db("test");

  $sql = "select members.name as mem_name,departments.name as dep_name 
  from members 
  left join department 
  on 
  members.department_id = departments.id 
  order by members.name asc";

  $result = mysql_query($sql,$con);

  while ($row=  mysql_fetch_array($result)) 
  {
     echo '<optgroup label="'.$row['dep_name'].'">\n';
     echo '<option value="'.$row['mem_name'].'">'.$row['mem_name'].'</option>\n';
     echo '</optgroup>\n';  
  }
  ?>

结果:

enter image description here