Multiple initially selected values in a dynamic select list with PHP
Thanks in advance for your help. This list is to update an existing record, so it's populated from a database with $rs_fullcat
then checked with another recordset $rs_cat
for the initially selected values. I can on开发者_运维知识库ly get it to initially select one value, the first one in $rs_cat
, but I need it to select all of the existing options from the database. I feel like I'm close but I can't find the answer anywhere. Here's the code:
<select name="category" multiple="multiple" id="category">
<?php
do {
?>
<option value="<?php echo $row_rs_fullcat['categoryID']?>"<?php if (!(strcmp($row_rs_fullcat['categoryID'], $row_rs_cat['categoryID']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_fullcat['category_name']?></option>
<?php
} while ($row_rs_fullcat = mysql_fetch_assoc($rs_fullcat));
$rows = mysql_num_rows($rs_fullcat);
if($rows > 0) {
mysql_data_seek($rs_fullcat, 0);
$row_rs_fullcat = mysql_fetch_assoc($rs_fullcat);
}
?>
</select>
What you want to do, is first select (and fetch) all the selected ones from the database, and put them in a variable ($rs_cat
in your case). Then, in your while
loop it's a simple matter of doing an in_array()
check to see if the value is selected.
精彩评论