views:

156

answers:

3

How to make <option selected="selected"> set by MySql and PHP?

My code:

echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
    $r = mysql_fetch_array($rs);
    //if($year==$r["year"]){ $selected=' selected="selected"'; }//doesn't work so
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option>".$r["year"]."</option>";//<option$selected>...
    }
}
unset($tempholder);
echo '</select>';
+2  A: 

You must define $selected everytime, and you were using the assignment operator instead of the comparison:

echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i = 0; $i < $nr; $i++){
    if($year == $r["year"]) { //not $year = $r["year"]
        $selected=' selected="selected"';
    }
    else {
       $selected = "";
    }
    $r = mysql_fetch_array($rs);
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option$selected>" . $r["year"] . "</option>";
    }
}
unset($tempholder);
echo '</select>';
Artefacto
@Artefacto: Unfortunately it **does not work so**, it keeps always `selected` option to the same value (to the latest `year`: 2010).
Binyamin
@Binyamin I didn't quite get what you want, but try this code -- certainly $selected is not constant.
Artefacto
+4  A: 

Try this one:

    echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
    $r = mysql_fetch_array($rs);
    if (!in_array($r['year'], $tempholder)){
        $tempholder[$i] = $r['year'];
        echo "<option".(($year==$r["year"])? ' selected="selected"' : '').">".$r["year"]."</option>";
    }
}
unset($tempholder);
echo '</select>';

It doesn't saves the state in a variable which you have to overwrite.

And I think the real error was the single equal sign in $year=$r["year"] and not wihtin the rest of the code.

Kau-Boy
@Kau-Boy: Thanks a lot! It works grate!
Binyamin
I am glad that could help you.
Kau-Boy
+2  A: 

In addition to fixing the =/== gotcha, you can save yourself the array lookup and make the code simpler by asking the database to return each year only once in the query:

<select>
    <?php $result= mysql_query('SELECT DISTINCT year FROM id ORDER BY year'); ?>
    <?php while($row= mysql_fetch_assoc($result)) { ?>
        <option <?php if ($row['year']==$year) { ?>selected="selected"<?php } ?>>
            <?php echo htmlspecialchars($row['year']); ?>
        </option>
    <?php } ?>
</select>

(You may not need htmlspecialchars() assuming that's a numeric year, but it's good practice always to HTML-escape any plain text you include in an HTML template. You can define a function with a shorter name to do the echo htmlspecialchars to cut down on typing. )

bobince
@bobince: What is the difference between your sample and @Kau-Boy code? Which one is faster, safer etc. ignoring `htmlspecialchars()` add?
Binyamin
The HTML-escaping is the only ‘safety’ issue here. As for speed, using the database rather than PHP to discard the duplicate years as in this answer would generally be faster (significantly faster if there is a *lot* of data), as in the original question code and Kau-Boy's version requires the entire contents of the `id` table to be extracted from the database and returned to PHP.
bobince
The other main difference is that I've changed the formatting to use PHP itself to template the content into HTML, rather than concatenating-then-echoing strings, and isolated the block structures (`while` in this case) in their own PHP tag. This allows a single, consistent indentation hierarchy. This is purely a stylistic choice, with little-to-no effect on performance, but I think readability is helped.
bobince
Thanks for explanation!
Binyamin