faqts : Computers : Programming : Languages : PHP : Database Backed Sites : MySQL

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

31 of 43 people (72%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do you make a pop-up select menu in a php page that is made up of entries from a table?

Jul 18th, 2000 12:03
Dan Thies, Michael Puglin, Mark McCray, www.webreference.com


Check out www.webreference.com they have just such an article on their 
website homepage right now.

=== If you just want to pull one column into the select ===
If you just want to pull one column from a table into the select, do it 
like this.  I'll assume you've already connected to the server and 
selected a database.  These examples use MySQL functions, but you can 
substitute the relevant functions for your database if you don't use 
MySQL:

<?php
$result = mysql_query("SELECT the_column_you_want FROM the_table");
while ($row = mysql_fetch_row($result))
  {
     echo "<option>";
     echo $row[the_column_you_want];
     echo "</option>\n";
  }
?>

=== If you want to pull two columns, one for the value ===
If you want to pull in two columns, with one for display in the Select 
menu, and one for the associated value, do it like this. For example, if 
you wanted to have a menu with the names of states, but have the form 
post the 2-letter abbreviation.

<?php
$result = mysql_query("SELECT * FROM the_table");
while ($row = mysql_fetch_row($result))
  {
     echo "<option value=\"";
     echo $row[name_of_value_column];
     echo "\">";
     echo $row[name_of_display_column];
     echo "</option>\n";
  }
?>

=== real-world example ===
Here's a code snippet from one of my projects, that creates a dropdown 
menu. I've set up a lookup table which uses the state's two-letter 
abbreviation as the primary key - column name is "id".  The table's 
other column "state" has the name of the state. I've added "ORDER BY 
state" to the query so that the list comes back in alphabetical order by 
state name. If you pre-sort your data before inserting it into a table, 
or you don't care what order it appears in, you could skip the ORDER BY 
in the query. 

<?php
$result=mysql_query("SELECT * FROM states ORDER BY state");
while($row = mysql_fetch_array($result))
{
 		 echo "<option value=\"";
		 echo $row[id];
		 echo "\">";
		 echo $row[state];
		 echo "</option>\n";
} 
?>