PHP从mysql填充下拉列表并获取ID

时间:2014-06-26 08:59:59

标签: php mysql arrays drop-down-menu

我试图搜索StackOverlow(和谷歌),但无法找到我要找的东西。

基本上我需要从mysql表中获取id和text的列表。

表:

ID:1 - 文字:Title1 ID:2 - 文字:Title2 等

但是我希望它用文本填充下拉列表,当我在下拉列表中选择一个项目时,它会给我该文本的ID(字符串或整数)。

所以,如果我选择Title2,它应该给我2

<?
include 'db.php';

$query="SELECT topic_id,topic FROM help_topic WHERE isactive=1 ORDER BY topic";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=category value='' id=category></option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[topic_id]>$nt[topic]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box

?>

1 个答案:

答案 0 :(得分:0)

使用循环生成这些值

<select>
<?php foreach ( $table_objects as $object){
   echo '<option value="'.$object['id'].'">'.$object['text'].'</option>';
}
?>
</select>