3

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>

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I hope you'd escape your HTML output if you were doing this for real.
you mean unescape? it should be like this: <?php echo "<select name='user'>"; while ($temp = mysql_fetch_assoc($query) { echo "<option value='".stripslashes($temp['id'])."'>".stripslashes($temp['name'])."</option>"; } echo "</select>"; ?>
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.
1

PHP Dynamic Drop-down

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.