Search code examples
phpradio-button

Radio Button Values From Comma Separated Values In PHP


I have stored questions and their Answer Values in mysql database table.

I want to fetch questions and their answer values as radio button.

How to achieve this ?

Current Code

id   |  question_field_name   |    question                |  answers
 1   |  gender                |    Gender ?                |  Male, Female, Transgender
 2   |  education             |    Education ?             |  Under Graduate, Graduate, Post Graduate
 3   |  like_reading          |    Do You Like Reading ?   |  Yes, No

I am using following php code to fetch questions and answers. I want to convert answers comma separated list as radio button

<?php
 $query = "select * from mytable";
 $result = $database->get_results($query);
 foreach ($result as $data){
    $field_name = $data['question_field_name'];
    $question = $data['question'];
    $answers = $data['answers'];
 ?>
 <label><?php echo $question;?></label>
     <input type="radio" name="<?php echo $field_name;?>" value="?"> 

    ### How to create here radio buttons with Answers in comma separated list stored in db in column answers
    if there are three values in comma separated list, then to create three radio buttons with each values, if two then two radio buttons ...etc...


<?php } ?>

Solution

  • You can use explode() to split the string into an array and then loop through it to generate the radio buttons.

    <?php
    $query = "SELECT * FROM mytable";
    $result = $database->get_results($query);
    
    foreach ($result as $data) {
        $field_name = $data['question_field_name'];
        $question = $data['question'];
        $answers = $data['answers'];
    
        // Split the answers into an array
        $answersArray = explode(',', $answers);
        ?>
        <div>
            <!-- show questuon here -->
            <label><?php echo htmlspecialchars($question); ?></label><br>
            
            <!-- answer radios -->
            <?php foreach ($answersArray as $answer): ?>
                <input type="radio" name="<?php echo htmlspecialchars($field_name); ?>" value="<?php echo htmlspecialchars(trim($answer)); ?>">
                <?php echo htmlspecialchars(trim($answer)); ?><br>
            <?php endforeach; ?>
        </div>
        <br>
    <?php
    }
    ?>