选择框:如何填充年数php [英] Select box: how to populate years php

查看:171
本文介绍了选择框:如何填充年数php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在php中填入一个生日字段多年的选择框。一个变量$ year是从一个查询设置的,那个特定的年份必须在我的选择框中被选中。到目前为止的代码是,它只是填充了几年,但它不选择存储在mysql数据库中的年份,有没有人知道为什么?谢谢

i'm trying to populate a select box in php for years in a birthday field. A variable $year is set from a query and that particular year has to be selected in my select box. The code so far is this, it just populates the years but it doesn't select the year that is stored in mysql db, does anyone knows why? Thanks

$year = $row['year']; // this comes from a query that is stored in the db
<select name="year"><?
    for ($x = 1920; $x < date('Y'); $x++) {
    ?><option value=<? echo $x; if ($x == $year) {echo 'selected="selected"';}?>><? echo $x;?></option><?
}?>
</select>


推荐答案

尝试这个:

$year = (int)$row['year']; // this comes from a query that is stored in the db
?>
<select name="year"><?php
    for ($x = 1920; $x < date('Y'); $x++) {
?><option value="<?php echo $x . '"'; if ($x == $year) { echo ' selected="selected"';}?>><?php echo $x; ?></option><?
}?>
</select>

主要问题是您没有关闭带有双引号,所以包含了'selected =selected。所以你得到这个:

The main issue was you didn't close the value with double quotes, so the 'selected="selected" was included. so you got this:

<option value=1990selected="selected">1990</option>

此外,您没有在< select之前关闭PHP标签

这篇关于选择框:如何填充年数php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆