PHP - Create a checkbox list dynamically

-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, however I have the difficulty of putting each item in a way that generates a checkbox list.

How to display this checkbox list dynamically?

Following the response from @fernandoandrade the above code is working.

    
asked by anonymous 06.07.2016 / 04:31

2 answers

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 declaring an array , that in the file that receives the post in> goes a array $_POST['categoria'] , which are the options marked by the user.

    
06.07.2016 / 05:38
1

You can have 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 would have to foreach to loop all items in your array of features.

    
06.07.2016 / 04:37