如何<option selected="selected">通过MySQL和PHP 进行设置?
<option selected="selected">
我的代码:
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>';
除了修复=/ ==gotcha之外,还可以通过要求数据库在查询中每年仅返回一次来保存数组查找,并使代码更简单:
=
==
<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>
(您可能不需要htmlspecialchars()假设这是一个数字年份,但是始终将HTML模板中包含的任何纯文本都用HTML转义是一种很好的做法。您可以定义一个名称较短的函数echo htmlspecialchars来减少输入。)
htmlspecialchars()
echo htmlspecialchars