php-多个选择字段-多次使用selected =“ selected”
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-多个选择字段-多次使用selected =“ selected”,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2381字,纯文字阅读大概需要4分钟。
内容图文
![php-多个选择字段-多次使用selected =“ selected”](/upload/InfoBanner/zyjiaocheng/675/8b2b3a9949f8416c9a54e3178c579e98.jpg)
我有一个像这样的多个领域:
<select name="excluded_groups[]">
<?php echo $foo->multi_group_select_options($group_ids, $excluded_id); ?>
</select>
我设法通过此函数从数据库中获取结果并将其放在< select>中,但是我无法设法保持选定的值处于选中状态.
第一个参数应将“ selected =“ selected”添加到提交之前标记的字段中,然后再提交,第二个参数阻止显示group_id(第2个参数应能正常工作).
这是功能…
/**
* group_options
* Get group names in the dropdown list
*/
public function multi_group_select_options($default = false, $exclude_id = '')
{
global $user;
$exclude_id = (isset($this->config['default_group'])) ? $this->config['default_group'] : 5;
$sql_where = ($user->data['user_type'] == USER_FOUNDER) ? '' : 'WHERE group_founder_manage = 0';
$sql_where_and = (!empty($sql_where)) ? ", AND group_id <> $exclude_id" : "WHERE group_id <> $exclude_id";
$sql = 'SELECT group_id, group_name, group_type
FROM ' . GROUPS_TABLE . "
$sql_where
$sql_where_and
ORDER BY group_name";
$result = mysql_query($sql);
$s_group_options = '';
while ($row = mysql_fetch_assoc($result))
{
/*if (is_array($default))
{
break;
$group_id = '';
foreach ($default as $key => $group_id)
{
$group_id = $group_id;
}
}
print_r($default);*/
$selected = ($row['group_id'] == $group_id) ? ' selected="selected"' : '';
$s_group_name = ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
$s_group_options .= '<option' . (($row['group_type'] == GROUP_SPECIAL) ? ' class="sep"' : '') . ' value="' . $row['group_id'] . '"' . $selected . '>' . $s_group_name . '</option>';
}
$db->sql_freeresult($result);
return $s_group_options;
}
我作为第一个参数放入的数组是完全有效的.它只是具有键和值的普通数组,其中值是组ID.
在while内尝试使用foreach-无效,与while循环外相同.
$default数组如下所示:
Array
(
[0] => 1
[1] => 7
[2] => 2
[3] => 3
)
解决方法:
您没有设置$group_id.以下代码将使用默认值数组和单个值:
if(is_array($default)) {
$selected = in_array($row['group_id'], $default);
} else {
$selected = !strcasecmp($row['group_id'], $default);
}
$selected = $selected ? ' selected="selected"' : '';
除此之外,请查看@Barmar在his answer中编写的注释,并使用htmlspecialchars转义任何动态文本,例如$s_group_name.
此评论与您的??特定问题无关,但是您仍然应该考虑它.
请停止使用古老的mysql_ *函数编写新代码.它们不再维护,社区已经开始deprecation process.相反,您应该学习准备的语句,并使用PDO或MySQLi.如果您想学习,请使用here is a quite good PDO-related tutorial.
内容总结
以上是互联网集市为您收集整理的php-多个选择字段-多次使用selected =“ selected”全部内容,希望文章能够帮你解决php-多个选择字段-多次使用selected =“ selected”所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。