Generate Drop Down From MySQL [closed]

2020-05-10 09:09发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 8 years ago.

I need to generate a drop down menu from data in a MySQL table.

From the table, it'll have to take the user id and the username.

Then it'll set the user id to option value and the username to what shows up in the drop down.

Could anyone show me some code for it? I'm having trouble making the following work:

$sql = "SELECT user_id, user_name FROM users";
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
  echo "<option value=\".$row['user_id'].\">.$row['user_name'].</option>\n ";
  echo "<option value=\"12275\">".$row['user_name']."</option>\n ";
}

回答1:

You have a couple of issues with your output. First, it's not clear from your example if you have the actual select element parent, and I'm not sure if browsers will display options without a parent select. Second, you are not escaping your array variables. So this might fix it:

$sql = "SELECT user_id, user_name FROM users"; $result=mysql_query($sql);

echo '<select name="users">';

while($row = mysql_fetch_array($result)) {
    echo '<option value="'. $row['user_id'] . '">' . $row['user_name'] . "</option>\n";
}

echo '</select>';


回答2:

The first result in Google came up with an example...

http://forums.devarticles.com/mysql-development-50/drop-down-menu-populated-from-a-mysql-database-1811.html

Try to do a little research before posting in the future.