我有一个多个字段,如下所示:
<select name="excluded_groups[]">
<?php echo $foo->multi_group_select_options($group_ids, $excluded_id); ?>
</select>我设法通过这个函数从数据库中获取结果,并将它们放入<select>中,但我不能设法保持选定的值。
第一个参数应该将selected="selected"添加到字段,这些字段在提交之前被标记,然后被提交,第二个参数阻止显示group_id (第二个参数的作用与它应该的一样)。
下面是函数...
/**
* 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;
}我作为第一个参数放入的数组是完全有效的。它只是一个包含键和值的普通数组,其中的值是组ids。
尝试在while循环中使用foreach -不起作用,在while循环之外也是如此。
$default数组如下所示:
Array
(
[0] => 1
[1] => 7
[2] => 2
[3] => 3
)发布于 2012-09-19 20:24:54
您没有设置$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。
发布于 2012-09-19 13:53:32
你的代码有几个问题。
首先,该函数将$exclude_id作为参数,但忽略该参数并为其赋值:
$exclude_id = (isset($this->config['default_group'])) ? $this->config['default_group'] : 5;其次,您说这应该是多选的,但是您的<SELECT>标记没有MULTIPLE属性。
第三,将$row['group_id']与$group_id进行比较。这只允许一个默认值,而不是多个,您甚至没有设置变量(设置它的代码被注释掉了,但它只会将它设置为$default数组的最后一个元素。DCoder的评论似乎是这个问题的正确解决方案。
https://stackoverflow.com/questions/12489034
复制相似问题