How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
问题描述
如何让被MySQL和PHP设置?
How to make <option selected="selected">
set by MySQL and PHP?
我的代码:
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>';
推荐答案
除了修复 =
/==
问题之外,您还可以省去数组查找和通过要求数据库在查询中每年只返回一次,使代码更简单:
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>
(您可能不需要 htmlspecialchars()
假设这是一个数字年份,但总是对 HTML 模板中包含的任何纯文本进行 HTML 转义是一种很好的做法.您可以使用较短的名称来执行 echo htmlspecialchars
以减少打字.)
(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.
)
这篇关于如何使<option selected=“selected">由 MySQL 和 PHP 设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使<option selected=“selected">由


基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01