Jump to content

[SOLVED] adding a dropdown to a form from a db table


Albatross

Recommended Posts

Evening everyone :)

 

What i'm trying to accomplish is to have my html form have an element that includes a dropdown menu that's fed from a list of names from an existing mysql db table.

 

i.e.

 

<select name="ban">
  <option selected>None</option>
  <option value="30 Day">30 Day</option>
  <option value="60 Day">60 Day</option>
  <option value="90 Day">90 Day</option>
  <option value="180 Day">180 Day</option>
  <option value="1 Year">1 Year</option>
  <option value="Lifetime">Lifetime</option>
</select><br><br>

 

Where this code is actially coming from xtable on y database.  I know how to connect to the db table in my connection code, but dont know how to get the drop down to show.

 

The purpose for this is because I want to be able to add names to the dropdown without editing the code for the forms, backend for processing pages, and output pages.  By updating a single table that reflects dynamically, I hope to save time and effort here.

Link to comment
Share on other sites

<?php
//Connect to DB
$query = "Select * from xtable"; //Adjust as needed
$result = mysql_query($query);
echo "<select name=\"ban\"><option selected>None</option>";
while($row = mysql_fetch_array($result)) //Loop through all results
{
       echo "<option value=\"".$row['nameoffield']."\">".$row['nameoffield']."</option>"; //Echo out the HTML
}
echo "</select>";
?>

 

Something like this should work for you. You will need to adjust the variable and query to suit your table layout.

Link to comment
Share on other sites

Assuming you have already connected to the database:

 

<?php
$optionQuery = "SELECT name, value FROM xtable";
$optionResult = mysql_query($optionQuery);

if (mysql_num_rows()) {
 //error handling when there are no options

} else {
 echo "<select name=\"ban\">";
 while ($option = mysql_fetch_assoc($optionResult) {
   echo "<option value=\"{$option['value']}\">{$option['name']}</option>";
 }
 echo "</select>";
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.