View Full Version : MySQL Fields In A Drop Down Option Form

12-23-2007, 03:49 PM
Lets say I have the following table in mysql....

Field Name - |db1|db2|db3|db4|db5|
Data - |db1|db2|db3|db4|db5|

Lets say I want to put all those data entries into a drop down list...

while ($row = mysql_fetch_array($result)){
echo '<select size="1" name="db">';
echo '<option value="'.$row['db1'].'">'.$row['db1'].'</option>';
echo '<option value="'.$row['db2'].'">'.$row['db2'].'</option>';
echo '<option value="'.$row['db3'].'">'.$row['db3'].'</option>';
echo '<option value="'.$row['db4'].'">'.$row['db4'].'</option>';
echo '<option value="'.$row['db5'].'">'.$row['db5'].'</option>';
echo '</select>';

My question is, can I do this a simpler way?

Field Name - |db1|db2|db3|db4|db5|
Data - |db1|db2|

So if only db1 and db2 has data, this means the drop down box will only have 2 options, but will still be fairly big in height!!

another e.g.

Field Name - |db1|db2|db3|db4|db5|db6|db7|db8|db9|db10|
Data - |db1|db2|db3|db4|db5|db6|db7|db8|db9|db10|

In this example it would get quite teadious having to script in each field into the drop down list. I'm expecting to use no more than 20db fields in total. This means I could either allow for 20 options in the drop down, or I'd like for there to be a way to only do a drop down list for ones that exist.

I do hope someone knows what I mean!!

Here is what I have so far but it outputs nothing at all in the drop down.

while ($row = mysql_fetch_array($result)){
echo '<select size="1" name="db">';
$numrows = mysql_num_rows($result);
for($i = 1; $i < $numrows; $i++){
echo '<option value="'.$row["db$i"].'">'.$row["db$i"].'</option>';
echo '</select>';

Thanks in advance.


12-24-2007, 03:34 AM
That should be simple. Put an if/else statement in the loop.


$table = "your Table";
$rows = MySQL_Query("SELECT * FROM $table");

print "<select name='something'>";

//Get a row
while($row = MySQL_Fetch_array($rows)){

//get a feild

//Grab an element in the array
$array = next($row); //A function I just learned :)

//make sure there is something in it
if($array != ""){

//echo it
echo "<option>$array</option>";



print "</select>";

I haven't tested it yet. . . But it's a start.

EDIT: It works!