Page 1 of 1

selecing items in listbox that are allready stored in sql

Posted: Mon Jun 30, 2008 7:43 pm
by psychotomus
Its currently selecting all items and not the 3 items that should already be shown.
anyone know whats wrong?

Code: Select all

                  <select name="select[]" size="10" multiple="MULTIPLE" id="select[]">
 
 
<?
    $cats[] = explode("|",$theme->cats);
    $result = mysql_query("SELECT * FROM cats ORDER BY name ASC");
    while($cat = mysql_fetch_object($result))
    {
                $found = false;
                for($i=0; $i<count($cats);$i++)
                {
                    if($cat->id == $cats[$i])
                    {
                        echo $cats[$i];
                        $found = true;
                        exit;
                    }
                }
                
                if($found == false)
                {
?>
                <option value="<?= $cat->id ?>"><?= $cat->name ?></option>
<?
                }
                else
                {
?>
            <option value="<?= $cat->id ?>" selected><?= $cat->name ?></option>
<?
                }
}
?>
                  </select>

Re: selecing items in listbox that are allready stored in sql

Posted: Mon Jun 30, 2008 8:34 pm
by Stryks
It's hard to say, not knowing what the data is ... but perhaps change ...

Code: Select all

<?
    $cats[] = explode("|",$theme->cats);
    $result = mysql_query("SELECT * FROM cats ORDER BY name ASC");
    while($cat = mysql_fetch_object($result))
    {
                $found = false;
                for($i=0; $i<count($cats);$i++)
                {
                    if($cat->id == $cats[$i])
                    {
                        echo $cats[$i];
                        $found = true;
                        exit;
                    }
                }
               
                if($found == false)
                {
?>
                <option value="<?= $cat->id ?>"><?= $cat->name ?></option>
<?
                }
                else
                {
?>
            <option value="<?= $cat->id ?>" selected><?= $cat->name ?></option>
<?
                }
}
?>
... to ...

Code: Select all

<?
    $cats[] = explode("|",$theme->cats);
    $result = mysql_query("SELECT * FROM cats ORDER BY name ASC");
    while($cat = mysql_fetch_object($result))
    {
        if(in_array($cat->id, $cats)) {
?>
            <option value="<?= $cat->id ?>" selected><?= $cat->name ?></option>
<?
        } else {
?>
            <option value="<?= $cat->id ?>"><?= $cat->name ?></option>
<?
        }
    }
?>
Is that doing the job?

Re: selecing items in listbox that are allready stored in sql

Posted: Mon Jun 30, 2008 9:39 pm
by psychotomus
works like charm. thanks =)