简体   繁体   English

使用HTML / PHP从SQL数据库创建列表

[英]Create a list from SQL database using HTML/PHP

Im trying to create a drop down list/menu of users from my SQL database table. 我试图从我的SQL数据库表创建用户的下拉列表/菜单。 Could anyone help me with the code please? 有人可以帮我解决这个问题吗? The code below is just for a normal list with options 1 & 2. How do i make the list retrieve all the items in a specific table using html/php/sql. 下面的代码仅用于包含选项1和2的普通列表。如何使用html / php / sql使列表检索特定表中的所有项目。 Sorry im not very experienced with this, thanks in advance. 对不起我对此不是很有经验,谢谢提前。

<select name="user" id="user">
<option value="a" selected="selected">1</option>
<option value="b">2</option>
</select>

there are several ways but i'll show mine 有几种方法,但我会展示我的

First, take the data you want to retrieve from query: 首先,从查询中获取要检索的数据:

$query = mysql_query("SELECT name, id FROM users");

Then echo a select followed by a while cycle to iterate the various options: 然后回显一个select后跟一个while循环来迭代各种选项:

<?php
echo "<select name='user'>";
while ($temp = mysql_fetch_assoc($query) {
    echo "<option value='".$temp['id']."'>".$temp['name']."</option>";
}
echo "</select>";
?>

The result should be: 结果应该是:

<select name="user">
   <option value='1'>User name 1</option>
   <option value='2'>User name 2</option>
</select>

Hope this was useful for you :) 希望这对你有用:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM