Php MySQL动态选择框

Php MySQL动态选择框,php,mysql,select,Php,Mysql,Select,我在MySQL中有两个表,使用的PHP类似于以下内容: ------------------------ | | | sizes | <--- This table is what populates the Select Box | | ------------------------ | id | name | |

我在MySQL中有两个表,使用的PHP类似于以下内容:

------------------------       
|                      |
|        sizes         |   <--- This table is what populates the Select Box
|                      |
------------------------
|    id     |   name   |
|           |          |           
|     1     |   Small  |
|     2     |   Medium |
|     3     |   Large  |
------------------------

----------------------------------------       
|                                      |
|            user_entries              | <--- This table relates to above by "size_id"
|                                      |
----------------------------------------
|    id     |   user_id  |   size_id   |
|           |            |             |
|     1     |     25     |      2      |
|     2     |     12     |      3      |
|     3     |     15     |      3      |
----------------------------------------
我的问题是:如何编写SELECT语句来填充包含所有大小选项(小、中、大)的选择框,并根据用户的偏好预先选择选项

例如,对于user_id=25的用户,HTML如下所示:

<select>
   <option>Small</option>
   <option selected="selected">Medium</option>
   <option>Large</option>
</select>
SQL是:

SELECT s.id, s.name, ue.id as UserSelected
  FROM sizes s
    LEFT JOIN user_entries ue ON s.id=ue.size_id AND ue.user_id=XXX
  ORDER BY s.id 
按你的要求来定顺序

在运行结果时,如果UserSelected不为NULL,即有一个值,则您拥有所选条目

SQL提示:尽量保持表之间的列名相同,以便size_id是size表中id字段的名称以及user_entries表中的外键;这样,在这个查询中就不会有两个会导致问题的id列


您可能也不需要user\u entries表中的id列,因为您总是基于user\u id进行搜索/更新?如果您不需要,只需少处理一列/索引。

因为您知道所有选项小、中、大,所以只需从第二个表中进行简单选择,即可按用户id获取用户的首选项。感谢您的回复。但是,我并不总是知道这些选项,因为它们是动态的,可以随时更改。对于这个问题,我只是尽量简化我的示例表。
// get size id from user entries table based on user id
$result2= mysql_query("SELECT size_id from user_entries where user_id='$user_id'");
$row2 = mysql_fetch_assoc($result2);
$sel_size_id =$row2['size_id'];

//dropdownlist query
$query="SELECT name,id FROM sizes";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);

//populate the dropdownlist
while($row = mysql_fetch_assoc($result)) { 
      //determine if the size id is selected
      $selected = ($row['size_id '] == $sel_size_id ) ? ' selected="selected" ' : NULL;
      echo  '<option value="' . $row['size_id']. '"' . $selected . '>'.$row['name'].'</option>\n';
}