tags:

views:

72

answers:

2

Im trying to create a drop down list/menu of users from my SQL database table. 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. 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>
+1  A: 

PHP Dynamic Drop-down

cmptrgeekken
+1  A: 

Hi, 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:

<?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 :)

Cristian
I hope you'd escape your HTML output if you were doing this for real.
grahamparks
you mean unescape? it should be like this:<?phpecho "<select name='user'>";while ($temp = mysql_fetch_assoc($query) { echo "<option value='".stripslashes($temp['id'])."'>".stripslashes($temp['name'])."</option>";}echo "</select>";?>
seventeen
No I mean something like echo "<option value='".htmlspecialchars($temp['id'])."'>".htmlspecialchars ($temp['name'])."</option>". Otherwise it's a potential HTML/Javascript injection security hole.
grahamparks