radio button selected according to BD in the foreach

0

Good morning, how can I make the radiobutton selected according to the database, I have a table in the bank with the categories being listed in a foreach on the radiobutton, until the beauty, it works to insert, but at the time of edit I need a radiobutton to be selected according to the id that is in the products table related to the id field of the category table, and in that part I am not able to do, my code below:

<?php
        foreach($listar_categorias as $categoria):
        if($categoria['id'] == $campos['categoria']){ $check = 'checked';}
?>
        <input type="radio" name ="cat_select" value="<?php $categoria['id']; ?>" checked="<?php echo $check; ?>" required="require" /><p><?php echo $categoria['nome']; ?></p>
<?php   
        endforeach;
?>

As the last option of the bank as in the radiobuttons is selected.

    
asked by anonymous 05.11.2018 / 12:15

1 answer

1

The problem is that the $check variable is not being cleared before scanning. That way all items after what really should be selected will also be with checked="checked" . Since the name property is equal, the last one with the checked="checked" property will always be marked.

The solution is to clear the variable check :

<?php
    foreach($listar_categorias as $categoria):
        $check = '';
        if($categoria['id'] == $campos['categoria']){
            $check = 'checked="checked"';
        }
?>
    <input type="radio" name ="cat_select" value="<?php $categoria['id']; ?>" <?php echo $check; ?> required="require" /><p><?php echo $categoria['nome']; ?></p>
<?php   
    endforeach;
?>

Notice that I changed the contents of the variable $check from checked to checked="checked" , this is because if the item should not be marked, nor does it need to declare the property checked .

    
05.11.2018 / 14:13