Jump to content

[SOLVED] Populating a drop down list from mysql


lmhart

Recommended Posts

I figured out how to populate a drop down list by hard coding it, but would really like to be able to do it from my database.  I found a sample of code but I can not get it to load the data into the drop down box.  I dont not understand the workings of the drop down box.  If someone could give me a simple example that would be great.

 

Thanks

 

 

 

<?php

include 'dbc.php';

$query="Select * from states";


$result = mysql_query ($query);
$options="";
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box 


?>

That is pretty much a simple example. There seem a few HTML issues with it and I'd change it to the following, but other than that, I'm not sure what your looking for. The table in the database would need a column or id and a column of name.

 

<?php
$query="Select * from states";
$result = mysql_query ($query);

echo '<select name="student">';
// printing the list box select command

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo '<option value="'.$nt['id'].'">'.$nt['name'].'</option>';
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box 
?>

The DB table is just a table that holds each states code.  Has one field named state.  That is why I am selecting all.  My issue is that the example I found has more then one field, so it is throwing me off.  It is wanting to return an "ID" and "Name" values.  Where I only have one field.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.