We'll start by assuming we have a table called 'users'. We're using MySQL, and we want a dropdown box containing all of our users from our users table, by name. So, we'll go step by step. I'll assume for the purposes of this tutorial that, prior to this code, the database connection has already been established. The first thing we'll want to do is to run our query to get the information into a result resource. Since we want to display their user names in the dropdown box, we can speed up the operation and use up less memory by pulling only the field that we need.
// Write out our query. $query = "SELECT username FROM users"; // Execute it, or return the error message if there's a problem. $result = mysql_query($query) or die(mysql_error());
Now $result contains the result resource we'll be using to populate our dropdown box.
Fast forward to where we'll actually be doing the HTML for the dropdown box. As you're probably aware, the dropdown box is a select element, and each choice is an option sub-element inside of the select. We can use string concatenation to build our dropdown box, and use the echo construct to output it afterward. We'll name our dropdown box 'users', in keeping with its contents.
$dropdown = "<select name='users'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
You'll notice that our dropdown box is output containing option elements for all of our users. To control that, make the dropdown box part of a form, and do a select statement based on the value of 'usernames', after it has been cleaned and validated (gotta watch out for spoofed pages), and you can make this a select box that control what information gets passed to the form for modifying information on users in your database.
I hope you find this helpful.





MultiQuote





|