問題描述
我已經閱讀了有關如何使用 MySQL 填充整個下拉列表的教程,但我遇到的問題是我只想從數據庫中獲取一個并將其作為選定的一個.所以我想要一個下拉列表,其中包含數據庫中的三個項目(Item1、Item2、Item3),它存儲在一個名為 itemschoice 的列中,該列的值為Item2".當我加載下拉框時,如何讓 item2 被選中?
I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?
推薦答案
在您的 元素中為
selected
屬性添加 中的值>itemschoice
.
In your <option>
element add the selected
attribute for the value that is in itemschoice
.
使用組合函數獲取選擇的粗略示例:
Crude example using a made up function to get the choice:
$choice = get_items_choice();
$results = mysqli_query($sql);
echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
if ($row['choice'] === $choice) {
echo '<option value="' . $choice . '" selected="selected" />';
} else {
echo '<option value="' . $choice . '" />';
}
}
echo '</select>';
這只是一個例子,不要復制&粘貼此內容而不添加某種錯誤驗證!
This is just an example, don't copy & paste this without adding some kind of error verification!
這篇關于PHP MySQL 下拉框填充選定值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!