Jump to content

Populate a drop down list


Lyleyboy

Recommended Posts

Hi all,

 

I have a users table, one of the fields is an evening (attendance to the club).

I want to be able to show a form with (amongst other things) the evening name in a drop down list. I'd like to pull the evenings from a table and then check the selected to the one from the recordset.

 

Does that make sense?

 

Any pointers would be great. Thanks

Link to comment
https://forums.phpfreaks.com/topic/151234-populate-a-drop-down-list/
Share on other sites

The HTML for a drop-down combo box looks like this:

<select name="myname"><option value="XX">YY</option></select>

 

myname: The identifying name PHP will use to access it

XX: The value for YY

YY: What the user sees in the list

 

If we're looping through a table (ie. times) and pulling out id and timename we can build it like this:

<select name="times"><?php
$query=mysql_query("SELECT id,timename FROM times");
while ($row=mysql_fetch_assoc($query)) {
  echo '<option value="'.$row['id'].'"'.($row['id']==$timeid ? ' selected="selected"' : '').'>'.$row['timename'].'</option>';
}
?></select>

 

The contents of the () inside the echo statement just check each id with $timeid (the input from the user) and if they match it makes that particular option the default option - handy if a user submits a form and they have to correct something.

 

To read the above select box use this:

$timeid=intval($_POST['times']);

Thanks for that. I think I have mislead you.

 

I have a table 'user detail' which has a field called 'night'.

When the registration form is filled out the 'night' is populated from a different table called 'nights' (Imaginative aren't I?)

So when the form to edit the users is displayed there will be a value in $row['night'].

I can happily populate a text box with the value but I'd like to have a drop down populated from 'nights' table and then add the selected=selected attribute to the select element.

 

I hope that make more sense. Sorry!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.