Dynamic Data in Dropdown menue?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
drcolossus
Forum Newbie
Posts: 5
Joined: Tue Mar 23, 2004 8:19 pm
Location: Japan

Dynamic Data in Dropdown menue?

Post by drcolossus »

Hello,
I would like to create a form which contains a drop down menue (<select><option><option>...) and this menue should display automatically the choice which is read in from a mysql database by PHP.
I have no clue about how to achieve that now. Would be nice if someone can point me to an example.
Deemo
Forum Contributor
Posts: 418
Joined: Sun Jan 18, 2004 11:48 am
Location: Washington DC

Post by Deemo »

Code: Select all

<?php
echo "<select name = 'Options'>";    //Start selection box

$query = "SELECT * FROM Table";    //Get Data from DB
$result = mysql_query($query) or die("Couldn't Execute Query ".mysql_error());

while ($row = mysql_fetch_array($result))
{
  echo "<option value = ".$row['Value'].">."$row['Name']."</option>";  //Add an option for every row in the DB
}

echo "</select>";
?>
That code is assuming $row['Value'] to be a column and $row['Name'] to be a column and u should change it to whatever is right for your code, the above is just an example
drcolossus
Forum Newbie
Posts: 5
Joined: Tue Mar 23, 2004 8:19 pm
Location: Japan

Post by drcolossus »

thanks Deemo! So far it's understandable! I just wonder how it's possible to have the selection (which the user makes on the dropdown menue) can be saved back into the mysql database and if the selected menue item can be displayed as a default when the data is read in again. usually the first item in the dropdown menue is always shown by default but if i saved for example menue item 3, can this item be shown by default when fetching the data into the form again?

thanks for all help!
RadixDev
Forum Commoner
Posts: 66
Joined: Sun Mar 14, 2004 11:27 am
Location: U.K.

Post by RadixDev »

Add a little tweak...
Assuming the data containing the selection menu is $_POST['selection']:-

Code: Select all

<?php
echo "<select name = 'Options'>";    //Start selection box 

$query = "SELECT * FROM Table";    //Get Data from DB 
$result = mysql_query($query) or die("Couldn't Execute Query ".mysql_error()); 

while ($row = mysql_fetch_array($result)) 
{ 
  if($row == $_POST['selection']) {
    echo "<option value = ".$row['Value']." selected>."$row['Name']."</option>";
  } else {
    echo "<option value = ".$row['Value'].">."$row['Name']."</option>";  //Add an option for every row in the DB 
  }
} 

echo "</select>"; 
?>
Post Reply