faqts : Computers : Programming : Languages : PHP

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

93 of 105 people (89%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How to extract data from database and display it in the list box?

Nov 27th, 2008 02:20
healthy man, 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 : [email protected]
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>
http://www.hostingping.com
http://www.alvantom.com
http://www.scriptstan.com
http://www.carscorals.com
http://www.cellphonesmobiles.com
http://www.toplawyersattorneys.com