Page 1 of 1

Populating drop down menu from database

Posted: Fri Jul 20, 2007 6:36 am
by olbas
Sirs,

I would appreciate some help in this matter as im probably going about it all wrong. The goal is to create a drop down menu which is populated from a table in a database and parse the selected item to $POST. The table has one column which is a list of locations. ie Brighton, Warwick, Stockholm etc.

Using a while loop:

Code: Select all

<select name="Location">
<?php 
while ($row = mysql_fetch_array($locationresult, MYSQL_NUM)) {
	printf("<option> %s </option>", $row[0]); 
}
?>
</select>
I have successfully populated the dropdown with the rows. However they have no "value" to parse to $POST and i am having trouble understanding how to achieve this.

I thought something like

Code: Select all

while ($row = mysql_fetch_array($locationresult, MYSQL_NUM)) {
	printf("<option value = %s> %s", $row[0], $row[0]);
}
would work and indeed achieves the same result as above however i still have no idea how to capture the selected item as a variable.

This project is for a local charity i have chosen to devote some time to and the system will (eventually) enable select members to mass email contacts by searching the database by location/group.

Any pointers would be greatly appreciated.

Posted: Fri Jul 20, 2007 6:59 am
by volka
When the browser submits the form all named (and successful) form items are send as name=value pairs to the server.
In your case the successful form item is the <select name="Location"> element. Depending on your form's method you can access the value via $_GET['Location'] or $_POST['Location']

Thank you!

Posted: Fri Jul 20, 2007 7:40 am
by olbas
Wow as easy as that!

so it seems i can use

Code: Select all

printf("<option> %s </option>", $row[0]);
just the same as

Code: Select all

printf("<option value = %s> %s", $row[0], $row[0]);
To achieve the same result (i need to learn the true difference between the two)

Thank you for helping a newb, this is awesome.

O
x

Posted: Fri Jul 20, 2007 5:39 pm
by feyd
Remember to quote attribute values.. (and likely run the values through htmlspecialchars()) .. or you'll post again with problems of partial information getting through... ;)