Problem with checkbox

Asked

Viewed 45 times

0

When I try to check through the database if any record exists, mark the checkbox as checked, always returns me as unchecked.

 <?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 

    }

?>

1 answer

1


You need an array, but you are overriding the variable $cat instead of making it an array of values. Follow 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 

    }

?>
  • I tried but still no score

  • This already worked had not seen its change

Browser other questions tagged

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