[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-general
Subject:    Re: [PHP] php forms - select menu selected behavior
From:       Ashley Sheridan <ash () ashleysheridan ! co ! uk>
Date:       2009-04-30 18:59:54
Message-ID: 1241117994.3494.140.camel () localhost ! localdomain
[Download RAW message or body]

On Thu, 2009-04-30 at 11:06 +0200, Marcus Gnaß wrote:
> Troy Oltmanns wrote:
> > I have the code below being used to rifle through a list of available
> > categories and create select options for them. The code is being used to
> > query the database and compare the product category to the current
> > iteration, if there's a match, then add selected code so the category is
> > prechosen. More code (not included) does the saving and all that, I've check
> > phpmyadmin. But when the page submits, the old category appears in the drop
> > down as selected. If I leave the page and come back it's fine, it's just
> > right after it is saved. The form script is being used on itself, in that
> > there is only one file for the form, the submission, etc. All of the other
> > input elements will load the data after being saved, is it something
> > specific to dropdowns, or it is the way the code is being instatiated?
> > 
> > All help is much appreciated. Please let me know if anymore info is needed.
> > 
> 
> //MAKE CATEGORIES DROPDOWN
> 
> $catlist1 = "";
> 
> // read product
> $catmatch = "SELECT prod_cat0 FROM product WHERE dbi='$dbi';";
> $catresult = mysql_query($catmatch);
> $catquery = mysql_fetch_array($catresult);
> 
> // read categories
> $sql = "SELECT category FROM categories ORDER BY category;";
> $result = mysql_query($sql);
> while ($col2 = mysql_fetch_array($result)) {
> 
> 	$id = $col2["category"];
> 
> 	if ($id == $catquery['prod_cat0']){
> 
> 		$catlist1 .= "<option value=\"$id\" selected=\"selected\">$id</option>";
> 
> 	}	else {
> 
> 		$catlist1 .= "<option value=\"$id\">$id</option>";
> 
> 	}
> 
> }
> 
> > 
> > to instantiate <?=$catlist1?>
> > 
> 
> The only data you need from table product is the column prod_cat0, from
> table categories it's category, so you should read only the needed data
> instead of using * for better performance.
> 
> Take the SQL and verify if it returns what you want it to return then.
> 
I tend to do my loops like this:

while ($col2 = mysql_fetch_array($result))
{
    $id = $col2["category"];
    $selected =($id == $catquery['prod_cat0'])?'selected="selected"':'';

    $catlist1 .= "<option value=\"$id\" $selected>$id</option>";
}

Just looks a little neater. 'Course, you could remove the $id line and
chuck the value straight into the short if statement there.


Ash
www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic