1

I have:

$selectedItem = '100,200,300';

And mysql load:

<select multiple="multiple" name="product_id">
   <?php
   $query = mysql_query("SELECT * FROM products ORDER BY id");
   while($row = mysql_fetch_array($query)){
      echo '<option value="$row[id]">$name</option>';
   }
   ?>
</select>

And I need $selectedItem (three values) to be:

<option value="$row[id]" selected>$row[id]</option>

How can I do that? I just can't find the solution when the selectedItem more than 1.

1
  • isn't this php? somebody pls use the right tags! Commented Nov 9, 2012 at 5:46

2 Answers 2

1

You should make your $selectedItem variable an array (and name it plural since it can have multiple values; just my added preference =P):

$selectedItems = array(100, 200, 300);

Doing this, you'll be able to check if the current row's id is in the array or not (with in_array()) and then "select" that row:

while($row = mysql_fetch_array($query)) {
    $selected = in_array($row['id'], $selectedItems) ? ' selected="selected"' : '';
    echo '<option value="' . $row[id] . '"' . $selected . '>' . $row['id'] . '</option>';
}

Alternatively, if you can't "define" your list of selected items as an array and you will only have a comma-separated string, you can use explode() to turn it into an array:

$selectedItems = explode(',', $selectedItem);

This will split the $selectedItem variable by commas into an array stored into $selectedItems (usable with the above code).

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this:

while($row = mysql_fetch_array($query)){
     if ( str_pos( $selectedItem.',' , $row[id].',' ) !== false) {
        $sel = 'selected';
     } else {
        $sel = '';
     }
     echo "<option value='$row[id]' $sel>$row[id]</option>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.