在数据库中显示逗号分隔的下拉值

时间:2016-04-25 05:16:17

标签: php mysql

我已将多个选项从下拉列表选择菜单保存到数据库字段中,并用逗号分隔。如何再次在下拉菜单中加载它们? 它们保存为:choice1choice2choice55等。目前我的查询加入了两个表格,它看起来像这样:

$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 t2program的值。如果列中只有一个值,则此查询显示结果。但是当用逗号显示错误

时保存了多个值
PHP Warning:  Invalid argument supplied for foreach()...

2 个答案:

答案 0 :(得分:2)

根据需要尝试使用program列值:

<?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']." ";
//$result = $pdo->query($sql);

echo '<select class="form-control" name="program">';
foreach ($pdo->query($sql) as $row_program){
    $options = $row_program['program'];// as you need this column values
    $optionsArr = explode(",", $options);   
    foreach ($optionsArr as $key=>$row){
        echo '<option value='.$row[$key].'>'.$row[$key].'</option>'; 
    }
}
echo '</select>';
?>

答案 1 :(得分:1)

explode()与逗号一起使用,以便为您提供一系列选项,然后在下拉列表中设置动态选项值。

<?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>';
?>