tatty27 tatty27 - 5 months ago 12
SQL Question

Delete database entry if checkbox is unchecked

I have a form that allows engineers to be added to a job by checking checkboxes which works fine. However, I would like the user to remove an engineer by unchecking their checkbox on another form.

The table (a many to many table) has 3 columns id_ce (the primary key), call_ce (foreign key) and engineer_ce (foreign key). I would like the form to check if a checkbox is empty and if it is check to see if there is an entry in the table with the call_ce and engineer_ce and delete it if it exists but I'm failing miserably.

This is what I have so far...

foreach($_POST['engineer'] as $engineer_id){
if(!isset($_POST['engineer'])){
$sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id' AND engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
if(mysql_num_rows($result) > 0){
$sql = "DELETE FROM calls_engineers WHERE engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
}
}
}


I suspect the problem may be something like the checkboxes that aren't checked don't post so they aren't going through the foreach loop but I'm not sure of another way of doing it.

Any help will be greatly appreciated

Answer

You can put on page a hidden field with engineer ids. Say, it will be called engineer_on_page

Now you can

foreach($_POST['engineer_on_page'] as $engineer_id) {
     if(!in_array($engineer_id, $_POST['engineer'])){
          //do delete here
     }
}

I expect that checkboxes looks similar to this:

<input type="checkbox" name="engineer[]" value="[engineer_id]"/>

and hidden field

<input type="hidden" name="engineer_on_page[]" value="[engineer_id]"/>

Also you may specify checkbox field like this:

<input type="checkbox" name="engineer[[engineer_id]]" value="[engineer_id]"/>

where [engineer_id] is actual id (1, 2,3 etc)

In second case you may use

     if(!isset($_POST['engineer'][$engineer_id])){
          //do delete here
     }
Comments