php 从 MySQL 数据库中获取数据到 html 下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10009464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetching data from MySQL database to html dropdown list
提问by ziz194
I have a web site that contains a html form, in this form i have a dropdownlist with list of agents that works in the company, i want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as a option in the drop down list .
我有一个包含 html 表单的网站,在这个表单中我有一个下拉列表,其中包含在公司工作的代理列表,我想从 MySQL 数据库中获取数据到这个下拉列表,这样当你添加一个新代理时,他的名字就会出现作为下拉列表中的一个选项。
Can you help me coding this php code please, thank you
你能帮我编写这个php代码吗,谢谢
<select name="agent" id="agent">
</select>
回答by SpaceBeers
To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.
为此,您需要遍历查询结果的每一行,并将此信息用于每个下拉选项。您应该能够很容易地调整下面的代码以满足您的需要。
// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}
echo '</select>';// Close your drop down box
回答by yasin
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
回答by fadedreamz
What you are asking is pretty straight forward
你问的很直接
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
对您的数据库执行查询以获取结果集或使用 API 获取结果集
循环遍历结果集或简单地使用 php 结果
在每次迭代中,只需将输出格式化为一个元素
the following refernce should help
以下参考应该有帮助
Getting Datafrom MySQL database
hope this helps :)
希望这可以帮助 :)

