radio button selected according to BD on foreach

Asked

Viewed 245 times

0

Good morning, as I can do to leave the radiobutton selected according to the database, I have a table in the database with the categories being listed in a foreach on the radiobutton, until then beauty, works to insert, but when editing I need a radiobutton to be selected according to the id that is in the products table related to the id field of the table of categories, 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;
?>

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

  • With this code what happens? Do any errors? Any radiobutton appears marked?

  • appears the last radiobutton marked, in all, once q and to appear marked in the option named in the bank

  • I imagined it was just that, I posted an answer.

  • very obg worked out

1 answer

1


The problem is that the variable $check not being cleaned before checking. That way all items after what should actually be selected will also be with checked="checked". Like property name is equal, the latter with the property checked="checked" will always be marked.

The solution is to clean 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 switched the contents of the variable $check of checked for checked="checked", because if the item should not be marked, nor need to declare the property checked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.