views:

1995

answers:

3

If in the browser I have parameters like:

http://localhost/specials.php?year=2009&make=honda&model=civic

and the dropdown looks something like this:

<select name="year">
<?php
$query = mysql_query("select distinct year from tbl_content where year = '$year'");
while($row = mysql_fetch_assoc($query)) {

echo "<option value=\"{$row['year']}\">{$row['year']}</option>";
}
?>
</select>


Now what I'm trying to do is show select when the dropdown options value is equal to the parameter year in the browser URL.

I tried this:

<select name="year">
<?php
$query = mysql_query("select * from tbl_year
while($row = mysql_fetch_assoc($query)) {

#=============================
if(isset($_GET['year'])) {

$year = (int)$_GET['year'];
if($year == $row['year'] { $selected = "selected"; }
else { $selected = "";
}


echo "<option value=\"{$row['year']}\" {$selected}>{$row['year']}</option>";
}
?>
</select>
+1  A: 

maybe try "selected='selected'" to make it valid xml

John Boker
A: 
<select name="year">
<?php

$selectedYear = NULL;

if(isset($_GET['year']))
    $selectedYear = (int)$_GET['year'];

$query = mysql_query('SELECT year FROM tbl_year GROUP BY year ORDER BY year ASC');

while($row = mysql_fetch_assoc($query)) {
    echo '<option value="' . htmlspecialchars($row['year']) . '"';

    if($selectedYear === (int)$row['year']) {
         echo ' selected="selected"';
    }

    echo '>' . htmlspecialchars($row['year']) . '</option>";
}

?>
</select>
strager
Note: I'm not sure on the SQL. Feel free to correct me.
strager
A: 

Fell free to separate functionality!

<?php
function selectList($name,$values,$labels=null,$selected=null){
if($labels==null) $labels=&$values;
    $data="<select name='$name'>";
    foreach($values as $k=>$v){
     $selected=($v==$selected)?'selected="selected"':false;
     $data.="<option value='$v' $selected>".htmlspecialchars($labels[$k])."</option>";
     }
     $data.="</select>";
     return $data;
}

$select=isset($_REQUEST['year'])?(int) $_REQUEST['year']:null;
$query=mysql_query("SELECT DISTINCT `year` FROM `tbl_year` ORDER BY `year`");
while(($row=mysql_fetch_assoc($query))!==false){
    $values[]=$row['year'];
    }
echo selectList("year",$values,null,$select);
?>
Anton