• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 316
  • Last Modified:

retain value in multi-select box on edit page

I have a multi-select box on my edit page which doesn't retain the values that are in the database when I edit it.  the selection is stored as an array in the db.  so a subject could have an array of 9, 10, 25 and so forth...just means that it belongs to more than one topic.

here's the code I have so far:

<SELECT name='id[]' multiple size=5>
 <?php                $tQuery = mysql_query("SELECT id, topic FROM topics ORDER BY topic");
                      while ($sRow = mysql_fetch_row($tQuery))
if( $id == $sRow[0] ) {
print ("<OPTION SELECTED value='$sRow[0]'>$sRow[1]</OPTION>");
} else {
print ("<OPTION value='$sRow[0]'>$sRow[1]</OPTION>");
} // end of conditions
} // end of while loop
  • 2
1 Solution
Hi lienny,

ok, let's assume that you have selected values in array $selectedIDs

    $selectedIDs = array(9, 10, 25);
<select name='id[]' multiple size=5>
    $result = mysql_query("SELECT id, topic FROM topics ORDER BY topic");
    while ($row = mysql_fetch_row($result)) {
        if (in_array($row[0], $selectedIDs)) {
            echo ("<OPTION SELECTED value='$row[0]'>$row[1]</OPTION>");
        } else {
            print ("<OPTION value='$row[0]'>$row[1]</OPTION>");


German Rumm.
liennyAuthor Commented:
i would like to do this dynamically.

Then you need to create $selectedIDs array dynamically.

For example, you have a table tblUserGroups:

UserID      GroupID

The data in it looks like this:

UserID         GroupID
username    9
username    10
username    25

    $sql = 'SELECT GroupID FROM tblUserGroups WHERE UserID = "username"';
    $result = mysql_query($sql);
    $selectedIDs = array();

    while ($row = mysql_fetch_row($result)) {
        $selectedIDs[] = $row[0];

    //    here you go, dynamically populated from db $selectedIDs array.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now