Problem with checkbox

0

When I try to check the database if any registry exists, check the checkbox as checked, it always returns me as not checked.

 <?php 

    $result_cat = $conexao->prepare("SELECT * FROM colecoes WHERE activo = :activo");
    $result_cat->bindValue(':activo', 1, PDO::PARAM_INT);
    $result_cat->execute();
    $row_cat_l = $result_cat->fetchAll(PDO::FETCH_OBJ);

     $qtd = count($_REQUEST['categorias_estabelecimentos']);

     for ( $i = 0; $i < $qtd ; $i++ ) {

        $cat = $_REQUEST['categorias_estabelecimentos'];

     }

    foreach ($row_cat_l as $row_cat) {

?>

        <label class='checkbox inline'>
            <input type="checkbox" <?=(in_array($row_cat->slug, $cat)?'checked="checked"':NULL)?> name="categoria[]" value="<? $row_cat->slug; ?>" />
            <?= $row_cat->titulo; ?>
        </label>


<?php 

    }

?>
    
asked by anonymous 31.03.2015 / 01:03

1 answer

1

You need an array, but you are overwriting the $cat variable rather than making it an array of values. Here's some suggestion.

<?php 

    $result_cat = $conexao->prepare("SELECT * FROM colecoes WHERE activo = :activo");
    $result_cat->bindValue(':activo', 1, PDO::PARAM_INT);
    $result_cat->execute();
    $row_cat_l = $result_cat->fetchAll(PDO::FETCH_OBJ);

     $qtd = count($_REQUEST['categorias_estabelecimentos']);

     // PHP 5. Se o seu for mais antigo use $cat = array();
     $cat = [];

     for ( $i = 0; $i < $qtd ; $i++ ) {

        $cat[] = $_REQUEST['categorias_estabelecimentos'][$i]['slug'];

     }

    foreach ($row_cat_l as $row_cat) {

?>

        <label class='checkbox inline'>
            <input type="checkbox" <?=(in_array($row_cat->slug, $cat)?'checked="checked"':NULL)?> name="categoria[]" value="<? $row_cat->slug; ?>" />
            <?= $row_cat->titulo; ?>
        </label>


<?php 

    }

?>
    
31.03.2015 / 01:08