[英]MySQL Dynamic Select Box
我在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_entries表中的“id”列,因為你總是會根據user_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';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.