update multiple records with php mysql

Asked

Viewed 649 times

0

I have a form that lists several records and I want to update the status field of these records but at once but I am not able to.

my for and code:

<form id="form1" name="form1" method="post" action="">
<?php while($row_table = mysqli_fetch_array($table)) { ?>
  <td height="30"><input name="id[]" type="hidden" id="id[]" value="<?php echo $row_table['id'];?>" /></td>
  <td height="30"><?php echo $row_table['col1'];?></td>
  <td height="30"><?php echo $row_table['col2'];?></td>
  <td height="30"><?php echo $row_table['col3'];?></td>
  <select name="status[]" id="status[]">
    <option value="0"<?php if($row_table['status']==0) echo 'selected="selected"';?>>Novo</option>
    <option value="1"<?php if($row_parceiro['status']==1) echo 'selected="selected"';?>>Ativo</option>
    <option value="2"<?php if($row_parceiro['status']==2) echo 'selected="selected"';?>>Inativo</option>
    <option value="3"<?php if($row_parceiro['status']==3) echo 'selected="selected"';?>>Rejeitado</option>
  </select>
  <input type="submit" name="atualizar" id="atualizar" value="Atualizar" />
<?php } ?>
</form>

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

        $query = mysqli_query($con,"update table set status = '$status' where id = '$id'");
        echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
        ++$i; 
    }
}           
?>

1 answer

2

The solution to the problem is very simple, so also you avoid sql Injection:

<?php

function submitList($post = array(), $con)
{
   if (count($post['id'])) {
      foreach ($post['id'] as $k => $id) {
          $status = (int) $post['status'][$k];
          $id = (int) $id;
          $stmt = mysqli_prepare($con, "UPDATE table SET = ? WHERE id = ?");
          mysqli_stmt_bind_param($stmt, "ii", $status, $id);
          mysqli_stmt_execute($stmt);
      }
     return true;
   }
   return false;
}

if ($_POST) {
    if (submitList($_POST, $con)) {
       echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index.php">';
   } else {
      echo "- Não há registros para serem enviados:\n<br><pre>";
      print_r($_POST);
      echo '</pre>';
   }
} 
  • hi @Ivan, tested and is not updating...

  • What problem is occurring?

Browser other questions tagged

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