update multiple records with php checkbox mysql

0

I need to update a mysql table with data coming from a / two checkbox where checked is 2 and unchecked is 1.

It turns out that if you check the id1 of col1 it will update id4.

What will be wrong?

My mysql table looks like this:

id col1 col2
1    1    1
2    2    1
3    2    1
4    1    2
5    1    2
6    1    2
7    1    2

The way I mounted the update:

I use a form as shown below:

<form id="form2" name="form2" method="post" action="<?php echo $PHP_SELF;?>">

my checkbox plus the id:

<input name="id[]" id="id" type="text" value="<?php echo $row['id'];?>" /> 

<input name="col1[]" type="checkbox" id="col1[]" value="2" <?php if($row['col1']==2) echo 'checked="checked"';?> />

<input name="col2[]" type="checkbox" id="col2[]" value="2" <?php if($row['col2']==2) echo 'checked="checked"';?> />

My code on the page itself:

<?php
    if(isset($_POST)){
        //-->
        $count = count($_POST['id']); 
        $i = 0; 
        //-->
        while ($i < $count) { 
            $id = $_POST['id'][$i]; 
            $col1= $_POST['col1'][$i]; 

            //-->
            $query = "UPDATE table SET col1= '$col1' WHERE id = '$id'";
            mysqli_query($con,$query);
            //-->
            echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
            ++$i; 
        }
    }
?>
    
asked by anonymous 01.03.2016 / 02:34

1 answer

1

Good morning, try this way

<script>
   function atualizar(id){
      var ck = document.getElementById(id).checked; //verifica se o checkbox estamarcado
      if(ck){ // se estiver marcado
         $("#res").load("atualizar.php", {id:id, valor:2}); //passa o id e o novo valor para a pagina de atualização
      }
      else{ //caso não esteja marcado
         $("#res").load("atualizar.php", {id:id, valor:1}); //passa o id e o outro valor para a pagina de atualização
      }
   }
</script>

Just include the onchange event in the input and pass the id as a parameter, the script will check if it is checking or unchecking the checkbox, and for each of the two options it will go to update page a new value and the id that should be updated in bd. Of course, create a div with id res to contain the update page!

    
01.03.2016 / 12:06