SQL Dropdown Box

Soldato
Joined
30 Nov 2005
Posts
3,084
Location
London
Just wondered if its possible to have data from a database presented in a drop down box using SQL and PHP.

I'm sure it's a SELECT statement and Print but can't quiet work out how.

Thanks for any help.
 
Id say that you can pretty much have any content in a select drop down.

Just do your query/ies in php and get the results, and then display whatever data you want to display between the <option> tags. e.g.

Code:
<option><?php echo $res['data']; ?></option>

That should do the trick.
 
Asuming you're using PHP and MySQL :p
I had trouble with this a few weeks ago. Here's what worked for me:

Code:
<select name="dropdown">
<?php do { ?><option value="<?php echo [B]$option_value[/B] ?>"><?php echo [B]$option_text[/B] ?></option><? } while ([B]$Query_Row[/B] = mysql_fetch_assoc([B]$Query[/B])); ?>
</select>
Its a bit primative, but it works. The bold bits are the parts which need changing.
$Query is obviously your SQL query. You also need to have the following in the php code somewhere near (but underneath :p) $Query:
Code:
$Query_Row = mysql_fetch_assoc($Query);
HTH
 
The do/while syntax is indeed primitive, just opt for the standard while syntax:
Code:
<?php do { ?><option value="<?php echo $option_value ?>"><?php echo $option_text ?></option><? } while ($Query_Row = mysql_fetch_assoc($Query)); ?>
will become
Code:
<?php

/*
* Example query:
* SELECT `option`, `value` FROM `table`
*/

while($row = mysql_fetch_assoc($query)
	echo '<option value="', $row['value'], '">', $row['option'], '</option>';

?>
no point escaping for such small output.
 
A do{} will also fail horribly if there are no rows returned for whatever reason, and also involves the unnecessary repetition of the $Query_row line :)
 
Nearly there but they print as separate drop downs for each one.

I know its something to do with the Movenext but again my lack of knowledge fails me.

Code:
while (!$rs->EOF)
{
print "<select size='1' name='drop'>";
print "<option value = 'phonemodel'>$phones->value</option>";
print " </select>";
$rs->MoveNext();
}
 
You don't want to be printing a <select> in a loop, naturally:

Code:
<select size='1' name='drop'>

<?php

while (!$rs->EOF)
{
 echo '<option value = \'phonemodel\'>', $phones->value, '</option>';
 $rs->MoveNext();
}

?>

</select>
 
Back
Top Bottom