Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

prefilling forms with data from a database

Status
Not open for further replies.

mufka

ISP
Dec 18, 2000
587
US
Using PHP to access MySQL data. I am able to create a form that has editable fields which allow me to change data in the database. For example I use:
First Name: <input type="text" name="ud_firstname" value="<? echo $firstname; ?>">

as a form field and I can edit the data. What I need help on is using data from the database record to preset a drop down box. The <select> has different options than <input> and I don't know where to start.

Thanks
 
It's always when I get to the end of my rope and I post a question that I find that the answer is just one more hour of trial and error away.

I solved my problem by using:

Working: <select size="1" name="ud_working">
<option selected><? echo $working; ?></option>
<option>Yes</option>
<option>No</option>
</select>

 
Code:
$dropdownValues = array("apple"=>"apple", "orange"=>"orange", "banana"=>"banana");
$dbValue = $row['dropdownbox']; //value stored in database
echo "<select name=\"dropdownbox\">\r\n";
foreach ($dropdownValues as $value=>$text){
  $selected = ($value === $dbValue) ? "selected=\"selected\" : '';
  echo "\t<option value=\"$value\" $selected>$text</option>\r\n";
}
echo "</select>\r\n";

a small adjustment can be made for multi-select boxes.
 
Hi, better html would be:
Code:
<?php
function genSelected($value, $name, $selected="no") {
if ($selected != "no") {
  $selVar = " selected=\"selected\ ";
  }
else {
  $selVar = "";
  }
  return "\n\t<option value=\"{$value}\"{$selvar}>{$name}</option>\n";
}
?>

<select size="1" name="ud_working">
<?php echo genSelected($working, $working, "yes"); ?>
    <option value="Yes">Yes</option>
    <option value="No">No</option>
    </select>

You could also make more parametres and even maybe make a function that is so advanced it can create entire inputs, based on parametres.. You switch parametres and return inputs or whatever..

btw. you can also do:
Code:
<?=$foo?>
to parse variables.

Olav Alexander Mjelde
Admin & Webmaster
 
Sorry, I forgot to check the $value and $name. lol..
If they are empty, you would not want to return anything, except maybe <option value="">Choose</option>

Olav Alexander Mjelde
Admin & Webmaster
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top