torvald_helmer Posted May 4, 2007 Share Posted May 4, 2007 how to create a drop down list with data from a database? Quote Link to comment Share on other sites More sharing options...
trq Posted May 4, 2007 Share Posted May 4, 2007 Simple example. <?php // connect $sql = "SELECT data FROM tbl"; if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { echo "<select>"; while($row = mysql_fetch_assoc($result)) { echo "<option value='{$row['data']}'>{$row['data']}</option>"; } echo "</select>"; } } ?> Quote Link to comment Share on other sites More sharing options...
pocobueno1388 Posted May 4, 2007 Share Posted May 4, 2007 <?php //Select the data from the DB $sql = mysql_query("SELECT col1, col2 FROM tbl WHERE condition"); //Start dropdown echo '<select name="s_name">'; //Populate the drop down with results from the DB while ($row=mysql_fetch_assoc($sql)){ echo "<option>" . $row['col'] . "</option>"; } //end drop down echo '</select>'; ?> I can see someone posted while I was, but I might as well post mine too since I spent the time typing it, haha. Quote Link to comment Share on other sites More sharing options...
torvald_helmer Posted May 4, 2007 Author Share Posted May 4, 2007 Thanks guys!! Quote Link to comment Share on other sites More sharing options...
trq Posted May 4, 2007 Share Posted May 4, 2007 <?php //Select the data from the DB $sql = mysql_query("SELECT col1, col2 FROM tbl WHERE condition"); //Start dropdown echo '<select name="s_name">'; //Populate the drop down with results from the DB while ($row=mysql_fetch_assoc($sql)){ echo "<option>" . $row['col'] . "</option>"; } //end drop down echo '</select>'; ?> I can see someone posted while I was, but I might as well post mine too since I spent the time typing it, haha. Sorry, but thats a pretty bad example. Absolutely no error handling. Quote Link to comment Share on other sites More sharing options...
pocobueno1388 Posted May 4, 2007 Share Posted May 4, 2007 I understand I didn't do any error checking, I was showing her how to populate a drop down list as they asked, not teach them how to error handle. Quote Link to comment Share on other sites More sharing options...
eddedwards Posted May 4, 2007 Share Posted May 4, 2007 if u get your data into an array this simple example might be usefull. im not too hot on db stuff though. <?php $test_array = array(); $test_array[0] = "Yes"; $test_array[1] = "No"; $test_array[2] = "Maybee"; echo "<select name=\"test_select\" >\n"; foreach ($test_array as $option) { if ( isset($option) && $option == "Yes") { echo "<option value=\"" . $option . "\" selected>" . $option . "</option>\n"; } elseif ( isset($option) ) { echo "<option value=\"" . $option . "\">" . $option . "</option>\n"; } } echo "</select>"; ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.