根据数据库中的值检查复选框

时间:2012-02-15 20:34:14

标签: php mysql

我有一个从数据库中获取“分支”的代码。每家公司都可以拥有多个“分支机构”。

唯一的问题是,这是行不通的。你们能弄明白什么是错的吗?

$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);

while($rijbranche = mysql_fetch_assoc($querygetbranches))
{
    echo "<tr>";
    echo "<td width='400'>";
    echo $rijbranche['naam'];
    echo "</td>";
    echo "<td>";
    $get2 = "SELECT * FROM bedrijf_branche WHERE bedrijf_id = '$id'";
    $query2 = mysql_query($get2);
    while ($rij20 = mysql_fetch_assoc($query2))
    {
        $branche_id = $rij20['branche_id'];
    }
    if($branche_id == $rijbranche['id_branche']){
        ?>
        <input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" CHECKED></input>
        <?php
    }
    else
    {
        ?>
        <input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>"></input>
        <?php
    }
    echo "</td>";
}

2 个答案:

答案 0 :(得分:2)

尝试以下代码

<?php

$id = $_GET['id'];

// Output BRANCHES
$getbranches = "SELECT * FROM branches ORDER BY naam ASC";
$querygetbranches = mysql_query($getbranches);

while ($rijbranche = mysql_fetch_array($querygetbranches)) {
  echo '  <tr>' . "\n";
  echo '    <td width="400">' . $rijbranche['naam'] . '</td>' . "\n";

  // Output CHECKBOX
  $get2 = mysql_query("SELECT * FROM bedrijf_branche WHERE bedrijf_id = '" . $id . "' AND branche_id = '" . $rijbranche['id_branche'] . "'");
  $rij20 = mysql_fetch_array($get2);
  $branche_id = $rij20['branche_id'];

  if ($branche_id == $rijbranche['id_branche']) {
    $checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" checked="checked" />';
  }
  else {
    $checkbox = '<input type="checkbox" name="branche[]" value="' . $rijbranche['id_branche'] . '" />';
  }

  echo '    <td>' . $checkbox . '</td>' . "\n";
  echo '  </tr>' . "\n";
}

?>

我在上面的代码中找到了一些错误。

  1. 您正在错误地关闭<input>字段
  2. 您的第二个while()循环是不必要的,因为只应返回一行
  3. 您必须将branche_id添加到第二个mysql_query!
  4. 当您只需添加<?php ?>
  5. 时,请勿关闭并重新打开每个HTML行的echo代码

答案 1 :(得分:0)

您的HTML语法错误。 关闭输入标签的方式以及检查chechbox的方式是错误的 试试这个

    <input type="checkbox" name="branche[]" value="<?php echo $rijbranche['id_branche']; ?>" checked="checked" />