Populating drop down menu from database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
olbas
Forum Newbie
Posts: 2
Joined: Fri Jul 20, 2007 6:19 am

Populating drop down menu from database

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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']
olbas
Forum Newbie
Posts: 2
Joined: Fri Jul 20, 2007 6:19 am

Thank you!

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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... ;)
Post Reply