从数据库中的列中显示逗号分隔的下拉值 [英] Showing comma separated dropdown values from column in database
问题描述
我已将下拉选择菜单中的多个选项保存到数据库字段中,并用逗号分隔它们.我现在如何在下拉菜单中再次加载它们?它们被保存为:choice1
、choice2
、choice55
...等.目前我的查询加入了两个表,它看起来像这样:
I have saved multiple choices from dropdown select menu into database field and separate them with comma. How can I load now them in dropdown menu again?
They are saved as: choice1
,choice2
,choice55
...etc. Currently my query joining two tables and it's look's like this:
$pdo = Database::connect();
$sql="SELECT t1.*, t2.*
FROM form_fields t1, user_choices t2
WHERE t1.field_name = t2.field_name
and group_id=1 and user_id=".$_SESSION['user_id']."
echo '<select class="form-control" name="program">';
foreach ($pdo->query($sql) as $row_program){
echo '<option value='.$row_program['field_name'].'>'.$row_program['field_name'].'</option>';
}
echo '</select>';
所以我需要显示来自 user_choices t2
列 program
的值.如果列中只有一个值,则此查询会显示结果.但是当有多个用逗号保存的值时显示错误
So I need to display values from user_choices t2
column program
. This query showing result if there is only one value in the column. But when there is multiple value saved with comma showing error
PHP Warning: Invalid argument supplied for foreach()...
推荐答案
使用带逗号的 explode()
以便它为您提供选项数组,然后在下拉列表中设置动态选项值.
Use explode()
with comma so its give you array of options and then set dynamic option values in dropdown.
<?php
$pdo = Database::connect();
$sql="SELECT t1.*, t2.*
FROM form_fields t1, user_choices t2
WHERE t1.field_name = t2.field_name
and group_id=1 and user_id=".$_SESSION['user_id']." ";
echo '<select class="form-control" name="program">';
foreach ($pdo->query($sql) as $row_program){
$options = $row_program['field_name'];
$optionsArr = explode(",", $options);
foreach ($optionsArr as $row){
echo '<option value='.$row.'>'.$row.'</option>';
}
}
echo '</select>';
?>
这篇关于从数据库中的列中显示逗号分隔的下拉值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!