PHP - Pre-Select TWO or more items in a dropdownlist from Mysql Database data
<p>UPDATE: HAVE MANAGED TO GET THIS TO WORK
NOT 100% "WHY" BUT WORKS.</p>

<p>Will Post for anyone esle, though code is no doubt dodgey hehe total beginner.</p>

<p>SOLUTION:</p>

<p>in the FOR loop instead of:</p>

<pre><code>for ($i = 0; $i &lt; $length; $i++) {
    if ($selected == $value[$i]) { //$category ... //$val
        $selected = "selected";
    } else {
        $selected = "";
    }
</code></pre>

<p>I DELETED THE Else part of the Else If Statement to:</p>

<pre><code>for ($i = 0; $i &lt; $length; $i++) {
    if ($selected == $value[$i]) { //$category ... //$val
        $selected = "selected";
    }
</code></pre>

<p>And Magic ... it works ... tested on prioducts with 2,3 n 4 categories and seems t be working fine.
I guess the esle was somehow always leaving the $selected as "" whether it matched or not</p>

<p>Hope that helps someone, spend all day trying to google/figure it out hehehe</p>

<hr>

<p>Scenerio: a Product can belong to multiple Categories</p>

<p>Add product with a multiple="multiple" dropdown list works fine.</p>

<p>Edit Product, I'm trying to pre-populate the droplist with the Product's multiple categories</p>

<p>Have tried so many different ways, usually with one category only being selected instead of 2</p>

<p>this is the latest attempt.. which selects only 1 or the (in this case) 2 categories this product belongs to.</p>

<p>So: How to select multiple items in a dropdownlist</p>

<p>Thanks</p>

<p>Code:</p>

<pre><code>&lt;!--&lt;select name = "category" id = "category"&gt;--&gt;
&lt;select name = "category[]" id = "category" multiple = "multiple"/&gt;
&lt;?php
//
//$getCats = "SELECT category_id FROM oc_product_to_category WHERE product_id = '$targetID'"; //EG: 61,62,63
$getCats = "SELECT category_id FROM oc_product_to_category WHERE product_id = '$targetID'";
$catList = mysql_query($getCats);
//$value = Mysql_fetch_row($catList);
$value = "";
$test = "";

$i = 0;
$length = 0;

while ($row2 = mysql_fetch_array($catList)) {
    //$value .= $row2['category_id'];
    $value[] = $row2['category_id'];
}

$length = count($value);

//
//
//  $test .= $selected;

$result = mysql_query($getCategories);

while ($row = mysql_fetch_array($result)) {
    $selected = $row['category_id'];

    $test .= $selected;

    for ($i = 0; $i &lt; $length; $i++) {
        if ($selected == $value[$i]) { //$category ... //$val
            $selected = "selected";
        } else {
            $selected = "";
        }
    }
    echo '&lt;option value="' . $row['category_id'] . '" ' . $selected . ' &gt;' . $row['name'] . '&lt;/option&gt;';
    //echo '&lt;option value="' . $row['name'] . '"&gt;' . $row['name'] . '&lt;/option&gt;';
}

//
?&gt;
&lt;/select&gt;   &lt;!--  &lt;?php echo $selected . "-" . "  " . $length; ?&gt; --&gt;
&lt;br/&gt;Current Cats: &lt;?php echo $value[1] . "---" . $test . " ..." . $length; ?&gt; &lt;br/&gt;
</code></pre>
