Reputation: 563
I need help in this and am very confusing thinking how to do this.
I have a form, an update/edit form, inside it I have a multiple selected listbox.
In my database records:
ID Items
1 Apple
2 Banana
3 Orange
4 Pear
5 Starfruit
And whenever the user clicks on edit which brings them to this form where I have made the listbox highlighted according to their previous saved data.
When the user clicks update, the listbox in the update form will look like this:
<option selected>Apple</option> <-- highlighted
<option>Banana</option>
<option selected>Orange</option> <-- highlighted
<option>Pear</option>
<option selected>Starfruit</option> <-- highlighted
This is what the user will see according to their 1st chosen items which was saved previously.
Currently I'm doing hard coding it:
<?php
$select=mysql_query("select * from products_list where id='$id' ");
while($row=mysql_fetch_array($select)){
$product_category = explode("\n", $row['category']);
$i=0;
echo '<select name="product_category[]" id="category" size="9" multiple="multiple"><option value="Black" ';
if ($product_category[$i] == "Black" ){ echo 'selected="selected"'; $i++; }
echo '>Black</option><option value="White" ';
if ($product_category[$i] == "White" ){ echo 'selected="selected"'; $i++; }
echo '>Black</option><option value="Blue" ';
if ($product_category[$i] == "Blue" ){ echo 'selected="selected"'; $i++; }
echo '>Black</option>';
}
?>
And so on so forth. I only list a few. So I would like to ask is there a way that I can do this, if my listbox options are not hard coded?
Hope you guys understand. Thanks in advance.
Upvotes: 0
Views: 2226
Reputation: 1407
I'm sorry if i misunderstood you and your code but I think this is what you want to do:
<?php
$select=mysql_query("select * from products_list where id='$id' ");
// Insert the categories in an array in order
$categories = array('Black', 'White', 'Blue', ...);
while($row=mysql_fetch_array($select))
{
$product_category = explode("\n", $row['category']);
echo '<select name="product_category[]" id="category" size="9" multiple="multiple">';
foreach($product_category as $i=>$value)
{
echo '<option value="'.$categories[$i].'"';
if($value == $categories[$i])
{
echo ' selected="selected"';
}
echo '>'.$categories[$i].'</option>';
}
echo '</select>';
}
Upvotes: 1