PHP - Create a checkbox list dynamically

Asked

Viewed 1,139 times

-1

I have the following code, where I select categories from a MYSQL table.

<?php
include 'conect.php';
// array que conterá as categorias
$cats = array();



$sql = "SELECT id_carac, nome_carac FROM carac";
$exec = $con->query( $sql ) or exit( $con->error );
$i = 1;
while ( $f = $exec->fetch_object() )
{
    $cats[$i]['id_carac'] = $f->id_carac;
    $cats[$i]['nome_carac'] = $f->nome_carac;
    $i++;
}
foreach ($cats as $key => $value) {
echo "<label><input type='checkbox' name='categoria[]' value='{$value['id_carac']}' > {$value['nome_carac']}</label></br>";
}
?>

This way I can display the selected content, but I have the difficulty of putting each item in a way that generates a checkbox list.

How to view this checkbox list dynamically?

Following @fernandoandrade’s reply the above code is working.

  • Do not use stacksnippets unnecessarily, please read help and see the best ways to format text for specific situations: http://answall.com/help/formatting

  • Use HEREDOC to dynamically generate the list.

2 answers

1

You can make PHP generate HTML code through echo:

<?php echo '<input type="checkbox" name="'. $cats[$i]['nome_carac'] . '" value="' . $cats[$i]['nome_carac'] . '">' . $cats[$i]['nome_carac'] . '<br>';

You’d have to make a foreach to go around all the items in your feature array.

  • Friend thanks for the attention, but the doubt is to insert inside the loop, I gave an updated there but following this your syntax is giving error, I had done in a way that gave error, but appeared only the checkbox, without the value and only once... If you could take a look..

  • I had done so->>echo "<input type='checkbox' name='" . $arrayCats[ $i ]['carac']. " ' /> n";<<-- On the corresponding line, but only displays a box with no value... Although I’m seeing it right now in a pus value.... kkkk these hours tmb

1


<?php
$cat = [
    ['id' => 1, 'nome' => "Cat A"],
    ['id' => 2, 'nome' => "Cat B"],
    ['id' => 3, 'nome' => "Cat C"],
    ['id' => 4, 'nome' => "Cat D"],
];

foreach ($cat as $key => $value) {
    echo "<label><input type='checkbox' name='categoria[]' value='{$value['id']}' > {$value['nome']}</label>";
}
?>

The name you leave as if you were declaring a array, that in the file that receives the post of his form goes one array $_POST['categoria'], which are the options marked by the user.

  • Friend thanks for your attention... Funfou de voleio ! ;) Vlw

  • No reason, it’s always good to share knowledge.

Browser other questions tagged

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