BStud BStud - 7 months ago 26
SQL Question

Showing comma separated dropdown values from column in database

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


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()...

Answer

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