如果选中复选框,如何回显 'checked'

How to echo 'checked' if checkbox is checked

在我的表单的 "edit view" 中,我有一个复选框列表,我想检查 table book_have_languages 中的复选框(注意一本书可以有更多不止一种语言)。

代码:

<?php $query_c = mysqli_query($mysqli, "SELECT id_language, name_language FROM languages ORDER BY name_language;")
                                                        or die('error '.mysqli_error($mysqli));
while ($data_c = mysqli_fetch_assoc($query_c)) {
      echo "<div class='checkbox'><label><input type='checkbox' name='languages[]' value='$data_c[id_languages]'>$data_c[name_language]</label></div>";

      $sql = "SELECT id_book, id_language FROM book_have_languages WHERE id_book=3";
      $res = $mysqli->query($sql) or die("error: ".$sql);
      $results = array();
      while($row = mysqli_fetch_assoc($res)) {
         $results[] = $row;
      }
      foreach ($results as $result){
       if($result['id_language'] == $data_c['id_language']){
        echo"<div class='checkbox'><label><input type='checkbox' name='languages[]' value='$data_c[id_language]'checked >$data_c[name_language]</label></div>";
       }

      }


}
?>

结果:

如果我的table是:

id_book | id_language

3 - 2

3 - 5

3 - 6

已检查语言 2、5、6,但它们似乎是重复的。我如何在第一个 echo 中指示只显示 table 中没有的语言?

您正在循环浏览各种语言,而不是浏览一本书的语言。如果您的 table 与描述的一样,$data_idi 应该有多个结果,而您只匹配第一个。您也应该在这些结果中循环。

我是这样解决的:

<?php
$query_c = mysqli_query($mysqli, "SELECT id_language, name_language FROM languages ORDER BY name_language;")
                                    or die('error '.mysqli_error($mysqli));

while ($data_c = mysqli_fetch_assoc($query_c)) {
      $sql = "SELECT id_book, id_language FROM book_te_languages WHERE id_book='$_GET[id]'";
      $res = $mysqli->query($sql) or die("error: ".$sql);
      $results = array();
      while($row = mysqli_fetch_assoc($res)) {
         $results[] = $row;
      }

    echo "<div class='checkbox'><label><input type='checkbox' name='languages[]' value='$data_c[id_language]'";
    foreach ($results as $result){
       if($result['id_language'] == $data_c['id_language']){
         echo "checked";
       }
    } 
    echo ">$data_c[name_language]</label></div>"; 
}
?>