Basically your form
can 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 it will put the id of each item to be deleted.
The "secret" here (which is no secret, has in the PHP documentation) is to put the []
keys in the "name" property, for PHP to receive the data as array / p>
and in PHP this is enough:
if(!empty($_POST['deletar'])) {
foreach($_POST['check_list'] as $id) {
// Aqui voce faz a operacao com o ID desejado
}
}
Mounting the query of delete:
To delete, 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
}
Ideally, this should be optimized in a way to group the results in batches so that the IN clause of the query does not go gigantic:
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
}
}
In this way, every 50 records will be executed query . For consistency, it may be the case to group everything into a transaction , but then it already depends on the actual use case, as well as the sanitization of 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 actual case. Here's an "impromptu" example of doing it differently:
<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 form is not suitable for you because you need to have a list of IDs in advance, I just put as an example that there are several ways to manipulate syntax depending on the context.
An example where this syntax would make sense is if instead of a checkbox to delete, you have a radiogroup per item with "delete", " file, "" do nothing, "for example. But even so, I would have several other ways of solving the same problem.