fejmintv
fejmintv

Reputation: 31

When checkbox is checked insert data if checkbox is unchecked remove data

I need help.

I want to create a system when the checkbox is checked inserts data into the database when it is unchecked it removes it from the database. Maybe there is another solution

HTML

<div class="row">
    <div class="col-lg-9"><label for="vehicle1">Perm 1</label></div> 
    <div class="col-lg-3"><label class="switch"><input value="1" name="permchecked[]" type="checkbox"><span class="slider"></span></label></div>
</div>
<div class="row">
    <div class="col-lg-9"><label for="vehicle1">Usuwanie/Perm 2</label></div>  
    <div class="col-lg-3"><label class="switch"><input value="2" name="permchecked[]" type="checkbox"><span class="slider"></span></label></div>
</div>
<div class="row">
    <div class="col-lg-9"><label for="vehicle1">Perm 3</label></div>     
    <div class="col-lg-3"><label class="switch"><input value="3" name="permchecked[]" type="checkbox"><span class="slider"></span></label></div>
</div>

PHP

if(isset($_POST['u_permissions_update'])){
   if (isset($permcheckeds)){ 
        foreach ($permcheckeds as $permchecked) {
            $query = $db2->prepare("INSERT INTO permissions_users SET user_id = :u_permissions_update, permissions_id= :permchecked"); 
            $query->bindValue(':u_permissions_update', $u_permissions_update);
            $query->bindValue(':permchecked', $permchecked);                     
            $query->execute();     
            $_SESSION['success']  = "Work";   
        }          
    } else {
        $_SESSION['success']  = "Not Working";   
    }  
}   

DB permissions_users

permissions_users_id | permissions_id | user_id 

visualisation

Upvotes: 0

Views: 247

Answers (1)

imvain2
imvain2

Reputation: 15847

Since I'm not sure what javascript framework you are using if any, here is a blueprint to what you can do.

If you are planning on sending the data to the server when the switch is changed, you check the onchange for the checkbox and you don't need it to be an array. And submit the process that you want to happen along with the value of the permission to be changed.

var _checks = document.querySelectorAll("input[name=permchecked]");

_checks.forEach(function(el){
  el.addEventListener("change",function(){
    var field_data = {
      "process" : (this.checked) ? "add" : "delete",
      "permission": this.value
    };

    //using ajax, submit field_data to the server

  });
});

PHP

In your PHP, then check for process:

if(isset($_POST['process'])){
  if($_POST['process'] == "delete"){
  //delete from database where that permission equals the value passed plus that user. Even if the permission doesn't exist in the database already, still just run the single delete query. No reason to add an additional query to check that it exists.
 }
elseif($_POST['process'] == "add"){
  //add that permission to the database
 }
}

Upvotes: 2

Related Questions