Andre
Andre

Reputation: 893

Check Checkbox depending on value in database

I have an code that gets the 'branches' from the database. Each company can have multiple 'branches'.

Only thing is, that is doesn't work. Can you guys figure out what's wrong?

$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>";
}

Upvotes: 2

Views: 989

Answers (2)

Tom
Tom

Reputation: 3520

Try the following code

<?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";
}

?>

Found a couple of errors I fixed in the above code.

  1. You're closing the <input> fields incorrectly
  2. Your second while() loop is unnecessary as there should only be one row returned
  3. You have to add branche_id to your second mysql_query!
  4. Don't close and re-open your <?php ?> tags for every HTML line when you can just add an echo

Upvotes: 2

OrangeTux
OrangeTux

Reputation: 11461

Your HTML-syntax is wrong. The way you close the input tag and the way you want to check the chechbox is wrong Try this

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

Upvotes: 0

Related Questions