Entry
How to extract data from database and display it in the list box?
Feb 18th, 2008 00:03
dman, Chris Thompson, Narendra Jain, Naveen Ghanathe, http://www.ttnr.org
Lets take an example:
You need to read states tables and put it in a list dropdown box. The
code would look something like:
$db = mysql_connect("localhost","root");
mysql_select_db("mydb",$db);
$result = mysql_query("select state_id, state_text from states");
if ($result)
{
echo "<SELECT NAME='state_id'>";
while ($myrow = mysql_fetch_array($result))
{
echo "<OPTION VALUE=\"".$myrow["state_id"]."\">".
$myrow["state_text"]." </OPTION> ";
}
echo "</SELECT>";
}
Explanation:
First 3 statements ensure database connectivity, and selection and the
query for the table. $result stores the result of the query and
mysql_fetch_array puts the result in an array ($myrow) indexed by the
column name. So $myrow["state_id"] will return the value of state_id
and $myrow["state_text"] will return the name of the state. Please note
that I have used state_id as the field when we select a value and this
is the value passed to the further programs.
Chris : chris@thompsonbd.com
I like to seperate the html code and the php code, so this is how I
would to it.
<code>
<?
$db = mysql_connect('localhost','root');
mysql_select_db('mydb',$db);
$sql = "SELECT state_abbr, state_name
FROM states;";
$rs = mysql_query($sql);
while($row = mysql_fetch_object($rs)) {
$states .= '<option value="' . $row->state_abbr . '">' .
$row->state_name . '</option>';
}
?>
<html>
<body>
<form>
<select name="states">
<option value="FALSE">Select a State</option>
<?= $states; ?>
</select
</form>
</body>
</html>
</code>