Ogy
Ogy

Reputation: 107

Multiple select by array

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.

Upvotes: 1

Views: 221

Answers (2)

newfurniturey
newfurniturey

Reputation: 38436

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).

Upvotes: 1

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>";
}

Upvotes: 0

Related Questions