PDA

View Full Version : Drop down list help


heaps21
02-11-2004, 05:30 PM
Hi, I am trying to build a page which allows registered users to edit their details. The first field is "Title". I want this to be a drop down box as there are limited values. Now I have no problem in creating a dropdown box but I want it to default to the value they have already in the database.

Could anyone give me some pointers as to how is best to do this? Cheers, Andy.

bcarl314
02-11-2004, 05:46 PM
I'm assuming you know how to connect to the database and get the default value...

something like...

$id = mysql_connect(host, username, password);
mysql_select_db(dbname, $id);
$sql = "SELECT value FROM table WHERE userID=$userID";
$rs = mysql_query($sql, $id);
$r = mysql_fetch_assoc($rs);
$value = $r['value'];
mysql_free_result($rs);



Then just echo out the value in your input tag


<input type="text" name="fieldName" value="<?php echo $value;?>" />


<edit>
opps, sorry you wanted for a drop down...


<select name="myselect">
<option value="value1" <?php if($value=="value1"){echo selected=\"selected\";}?>>Option 1</option>
<option value="value2" <?php if($value=="value2"){echo selected=\"selected\";}?>>Option 2</option>
</select>


</edit>

heaps21
02-11-2004, 07:17 PM
Thats a great help, thanks. Did it slightly differently but same idea. Im having a problem now though, were i can populate the dropdown but it always misses the first entry from the db table. I assume its something to do with the way the arrays are indexed. This is what i have:


print "<select>";
while ($row=mysql_fetch_array($result)){
$title=$row["title"];
print "<option value='$title'>$title</option>";
}



if this is more of a mysql question then i apologise but if anyone can help it would be much appreciated :)