update multiple records with php mysql checkbox

Asked

Viewed 985 times

1

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 id6 of the col1 it will update the 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 set up the update:

I use a form as shown below:

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

my checkbox plus 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; 
        }
    }
?>
  • Not updating only the first record because of the meta refresh? Try to put it after the while

  • Tip: I convert checkboxes to json and save them in the bank as a string, it’s easier to recover and add more options without having to change the database

1 answer

1

Good morning, try it 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 event onchange in the input and pass the id as parameter, the script will check if it is checking or unchecking the checkbox, and for each of the two options it will pass to the update page a new value and the id that should be updated in the bd. Of course create a div with id res to contain the update page!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.