Delete in multiple POSTS with checkbox

Asked

Viewed 353 times

1

I have already implanted on my site a link to each post that deletes through the ID in the database.

When you click the delete button, the link sends to the 'delete.php' page that executes the command and goes back to the previous page.

I would like to know how I do so that, through the HTML checkbox, I can select several posts and delete them at once?

Follow the posts listing script working:

<form action="deleta.php" method="post">
    <ul class="lista-posts">
        <li class="seleciona"><input type="checkbox" id="checkbox" name="deletar[]" value="<?php echo $row['id']; ?> " /></li>
        <li class="titulo"><?php echo '.$row['titulo'].'; ?></li>
    </ul>
</form> 

DELETA.PHP

if( !empty( $_POST['deletar'] ) ) {
   $groups = array_chunk( $_POST['deletar'], 50 );
   foreach ( $groups AS $group ) {
$group = implode('\',\'', $_POST['deletar']);
        $query = 'DELETE FROM conteudo WHERE id IN (\''. $group .'\')';
       $deleta = mysqli_query($conecta, $query);
      // executa a query
   }    
    if($deleta) {
       header("Location: ".$_SERVER['HTTP_REFERER']."");
       exit;
} else {
    echo mysqli_error($conecta);
}    
} else {
    header("Location: ".$_SERVER['HTTP_REFERER']."");
       exit;
}
  • 2

    Check this - http://answall.com/questions/92898/deletar-apenas-checkbox-selected-php/92917#92917

  • 1

    http://answall.com/a/7064/91

  • Post the entire error, not just a piece, missed to inform the file. A doubt, why your php is in French?

  • The error that appears on the page is only this. Well, whenever I get these type of errors with mysql database comes in French. In order to receive the error, I added an Else in the condition as follows: } Else ? echo mysqli_error($connects);

1 answer

3


Basically your form may have this structure:

<form method="post">
   <input type="checkbox" name="deletar[]" value="1" />Banana<br>
   <input type="checkbox" name="deletar[]" value="2" />Pera<br>
   <input type="checkbox" name="deletar[]" value="3" />Maçã<br>
</form>

Obviously, you will generate the inputs in a loop in PHP, and in value will put the ID of each item to be deleted.

The "secret" here (which is no secret, you have in the PHP documentation) is to put the keys [] in the "name" property, for PHP to receive the data as array

and in PHP just that:

if(!empty($_POST['deletar'])) {
   foreach($_POST['check_list'] as $id) {
      // Aqui voce faz a operacao com o ID desejado
   }
}


Riding the query delete:

To delete, effectively, you can use this syntax depending on the DB:

DELETE FROM minha_tabela WHERE ID IN ( id1, id2, id3, ... );

which can be easily mounted with PHP:

if(!empty($_POST['deletar'])) {
   $query  = 'DELETE FROM minha_tabela WHERE ID IN (';
   $query .= implode( ',', $_POST['deletar'] );
   $query .= ');';
   // executa a query
}

The ideal is that this is optimized in order to group the results in batches, not to become gigantic the IN clause of the query:

if( !empty( $_POST['deletar'] ) ) {
   $groups = array_chunk( $_POST['deletar'], 50 );
   foreach ( $groups AS $group ) {
      $query = 'DELETE FROM minha_tabela WHERE ID IN (' . implode( ',', $group ) . ');';
      // executa a query
   }
}

This way, every 50 records will be executed a query. For consistency, it may be the case to group everything into one transaction, but there already depends on the actual use case, as well as the sanitization of the input values.


Alternatives to other situations:

Nothing prevents you from using other structures, but it would be the case to choose the most suitable for the real case. Here is an "improvised" example of doing otherwise:

<form method="post">
   <input type="checkbox" name="id_1" value="x" />Banana<br>
   <input type="checkbox" name="id_2" value="x" />Pera<br>
   <input type="checkbox" name="id_3" value="x" />Maçã<br>
</form>

and in PHP:

foreach( $listaDeIds as $id ) {
   if( isset( 'id_' . $id ) {
      // Aqui voce faz a operacao com o ID desejado
   }
}

This second way is not suitable for your case because you need to have a list of Ids in advance, I just put as an example that there are several ways to move with the syntax depending on the context.

An example where this syntax would make sense is if instead of a checkbox to delete, you had one radiogroup by item, with options "delete", "archive", "do nothing", for example. But even so, there would be several other ways to solve the same problem.

  • 2

    As already had negative, I’m taking the opportunity to warn that if someone has suggested improvement or correction, or did not like the answer, can warn without fear, I do not return negative for revenge, as I had the impression that happens in Sopt sometimes. If it’s a good observation, I take it. If it’s not something I agree with, I can even explain why not. Incidentally, that’s why I could learn what I know today. Smart criticism teaches me more than compliments. But if the voter has nothing to say, it’s worth it too. I’m an advocate of people having the option to vote in secret here at Sopt.

  • Hello! Your answer was perfect. However, perhaps due to lack of understanding on my part, I felt the need to say that it seems to me that information is missing, or they are stamped on my face and I did not know how to use them. I will update my post and add the information and also how everything is happening, so you can help me again.

  • @Thiagobarros will try to adapt to the updates. Just explain to me the part where you say "several checkbox, because with your update I’m seeing a link pro delete, not a checkbox. The checkbox is to go in place of the link?

  • It is that in my system each post is generating a link to delete. In your opinion would redundancy leave the link and the checkbox? Because the link deletes a single id, and with the checkbox could delete several..

  • @Thiago, it’s hard for me to talk without visualizing what you’re imagining. I just think if it’s to delete with checkbox, there would be a bunch of them on the side of each post, and a button just to delete. If the guy wants to delete just one, he marks just one, no?

  • This really seems like the best way. So I guess I won’t need my link to delete the post anymore, will I? Now that you have the checkbox. Can you adapt the code? I tried and I couldn’t ..

  • Basically it is to exchange the link for <input type="checkbox" name="deletar[]" value="'.$row['id']'" />, before the loop put the <form action... and after the loop </form>. Then you need to decide where to put the delete button.

  • So far so good.. And how would be the page to delete, because the code Voce demonstrated is totally different from my current, which in case only works for a specific id..

  • @Thiagobarros the delete loop is the one I put, it’s practically ready, including with the query. Just a question of the delete button send to him. I gave 2 options inclusive, the 2nd is safer, that deletes in batches.

  • I received the following error: Erreur de syntaxe pr s de ')' la ligne 1. I updated my question upstairs, so you can see how I’ve assembled everything so far. Thanks again for your attention!

Show 5 more comments

Browser other questions tagged

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