如果数据库中存在值,请选中复选框

如果数据库中存在值,请选中复选框

问题描述:

I have a form that allows the user to add or remove users from a job by using checkboxes. At the moment the engineer's names etc are stored in a table called 'users' and they are identified by their user type, engineers. The checkboxes on the form are created by using a while loop to display a mysql query. This is done so that new users can be added to the database via a webpage at a later date and their name will automatically be added to the list of available engineers. To add an engineer to a job their name is simply ticked and the form submitted.

This works well but I would like the user to be able to add or remove users by checking and unchecking boxes on another form but I can't think for the life of me how to do this.

The users assigned to a job are stored in a many-to-many table called calls_engineers which has 3 fields

id_ce (unique id) call_ce (id of job, a foreign key) engineer_ce (id of engineer, a foreign key)

The engineer_ce is the users primary key in the 'users' table which is 'id'.

The code I have so far is...

<?  $sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id'";
      $result = mysql_query($sql) or die(mysql_error());
      $row2 = mysql_fetch_array($result);
      $sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
      $result = mysql_query($sql) or die(mysql_error());
      while ($row = mysql_fetch_array($result)){ ?>
          <div style="width:70px; float:left">
              <? 
                  if($row2['engineer_ce'] == $row['id']){
              ?>
              <input type="checkbox" name="engineer[]" checked="checked" value="<? echo $row['id']; ?>" />
              <? echo '   '.$row['first_name']; 
              } else { ?>
                  <input type="checkbox" name="engineer[]" value="<? echo $row['id']; ?>" />
              <? echo '   '.$row['first_name'];
              }?>
          </div>
  <?
      }

  ?>

All this does is create checkboxes for each user which is an engineer but it doesn't check them if the user is assigned to the job.

Any help will be greatly appreciated

You never loops the calls_engineers table. Using

$row2 = mysql_fetch_array($result);

Will not actually find all assignments for the engineer. Now check every single engineer if this is included in current job:

<?  

  $sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
  $result = mysql_query($sql) or die(mysql_error());
  while ($row = mysql_fetch_array($result)){ ?>

      <div style="width:70px; float:left">
          <input type="checkbox" name="engineer[]" <? 
              $result2 = mysql_query("SELECT * FROM calls_engineers WHERE call_ce = '".mysql_real_escape_string($diary_id)."' AND engineer_ce = ".$row['id']);
              if(mysql_num_rows($result2) > 0) echo 'checked="checked"';
             ?> value="<? echo $row['id']; ?>" />
          <? echo '   '.$row['first_name']; ?>
      </div>

  <? } ?>