Darkside
Darkside

Reputation: 11

Deleting from table if check box unticked

This is probably an easy one but I am stuck. I have a form with checkboxes that show employees and there skills, these are taken from a table with a many to many relationship. The below code works for updating the records but I am unsure on how to delete records if the checkbox is un-checked

$emp=$_POST['emp'];  

if(isset($_POST['chk1'])){
    $checkbox=$_POST['chk1'];
    $arr_num=count($checkbox);
    $i=0;

    while ($i < $arr_num)
    {
        $qry = "INSERT IGNORE INTO skillsets (skill_id, empr_id )VALUES(?, ?)";
        $stmt = $mysqli->prepare($qry);
        $stmt->bind_param('ii', $checkbox[$i], $emp);
        $stmt->execute();
        $i++;
    }
}
 else .... delete from .....

I am not sure of the syntax for the else, can someone help me out?

Upvotes: 0

Views: 90

Answers (1)

Elon Than
Elon Than

Reputation: 9765

You can define hidden inputs for every checkbox (before it) with the same name. Eg.

<input type="hidden" name="items[1]" value="no" />
<input type="checkbox" name="items[1]" value="yes" />

1 is your item ID. And now if checkbox is checked then its value will be send. In other case, value from hidden field will be send to your server. With this data you can iterate through items array, get ID from index and check value to know if it's checked or not.

Upvotes: 1

Related Questions