Delete only selected PHP checkboxes

0

I have a system that I did (I do not understand much of PHP) worked perfectly but after switching the server stopped the function of deleting only the selected checkboxes, it simply deletes everything.

I search all of them for database and command to display only the first 4 IDs (usually they are written with error in Bank - XML with problem that does not come from me).

Follows part of the code.

<form method="post" action="limpar_selecionados.php">
<?php
$query = sprintf("SELECT * FROM loja WHERE categoria = 'NOTEBOOK' ORDER  BY nome ASC  LIMIT 4");
$dados = mysql_query($query, $con) or die(mysql_error());
$linha = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
if($total > 0) {
do {
?>

<p> <input type="checkbox" name="chk[]" value="<?=$linha['id']?>"   style="display:block;"/> </p>

<?php
    }while($linha = mysql_fetch_assoc($dados));
}
?>

<?php
$query = sprintf("SELECT * FROM loja WHERE categoria = 'Smartphone' ORDER  BY nome ASC  LIMIT 4");
$dados = mysql_query($query, $con) or die(mysql_error());
$linha = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
if($total > 0) {
do {
?>

<p> <input type="checkbox" name="chk[]" value="<?=$linha['id']?>"   style="display:block;"/> </p>

<?php
    }while($linha = mysql_fetch_assoc($dados));
}
?>

<input type="submit" name="submit" value="Excluir Selecionados">

</form>

Clear_selected.php

<?php
print_r($_POST); 
    if(isset($_POST['chk'])){
            $excluir = $_POST['chk'];

            foreach ($_POST['chk'] as $item) {
            $sql_deleta = "DELETE FROM 'loja' WHERE 'id' = '$item'";
            mysql_query($sql_deleta);
}
}
?>
    
asked by anonymous 16.10.2015 / 22:40

4 answers

1

Why do not you organize id into a single variable, and then run as a single query? Another thing, is that you are passing the identifier in the value attribute, it is unnecessary when you already have that value in the name attribute.

To be honest, I do not exactly remember, and I do not know if that is the correct line of thought, but I can say that it is incorrect to sign values that are not true or false or equivalent to checkboxes . Someone to correct me if I'm wrong.

From:

<input type="checkbox" name="chk[]" value="<?=$linha['id']?>"/>

To:

<input type="checkbox" name="chk[<?=$linha['id']?>]"/>

In this part of the script, you could simply do:

if(isset($_POST['chk'])){
  $excluir = $_POST['chk'];

  foreach ($excluir as $item) {
          $sql_deleta = "DELETE FROM 'loja' WHERE 'id' = $item";
          mysql_query($sql_deleta);
}
}

I do not know if this is a custom function, created by yourself, or if it's just the old MySQL connection extension, because if it is, I recommend you start use MySQL or PDO .

mysql_query($sql_deleta);

Below is an example of how to execute queries as a single query by using the IN clause:

DELETE FROM tabela_ WHERE id IN (id1, id2, id3, idn...)

Example:

<?php
/* CREATE DATABASE IF NOT EXISTS exemplo; 
 * CREATE TABLE IF NOT EXISTS exemplo (
 * id INT(11) NOT NULL AUTO_INCREMENT,
 * titulo VARCHAR(20) NOT NULL,
 * PRIMARY KEY(id),
 * UNIQUE KEY(titulo));
 * INSERT INTO exemplo (titulo) VALUES ('primeiro'),('segundo'),
 * ('terceiro'),('quarto'),('quinto'),('sexto'),('setimo'),('oitavo')
 * ,('nono'),('decimo');
 */
$mysqli = new mysqli("localhost", "root", "", "exemplo");

if(!$mysqli) die ("Erro: " . $mysqli->connect_errno());
$consulta = $mysqli->query("SELECT * FROM exemplo ORDER BY id ASC");

if($consulta){
 echo "<form method=\"POST\" action=\"\">";
 while($linha = $consulta->fetch_object()){
  echo "<article style=\"display:block;\">" . $linha->titulo . "<input type=\"checkbox\" name=\"item[{$linha->id}]\"></article>";
 }
 echo "<input type=\"submit\" name=\"apagar\" value=\"apagar\">";
 echo "</form>";
} else {
 die("Erro");
}


if(isset($_POST["apagar"])){
  $ids = "";
 foreach($_POST['item'] as $id=>$val){
  $ids .= $id . ',';
 }
 $ids = substr($ids, 0, -1);
 $apagar = "DELETE FROM exemplo WHERE id IN({$ids})";
 if($mysqli->query($apagar)){
  header("Location: exemplo.php");
  exit();
 } else {
  die("Erro: ". $mysqli->error);
 }
}

?>
    
17.10.2015 / 00:49
0

Have you checked that the $ item variable has the correct values? and if the DELETE SQL is correct?

I also noticed that you create the variable $linha = mysql_fetch_assoc($dados); and then it creates it again in do {} while {} , I do not know if it gets in the way of something, I did not test, but I do not know if it helps.     

16.10.2015 / 23:01
0

Use this one and it will work:

<form method="post" action="limpar_selecionados.php">

<?php

$query = mysql_query("SELECT * FROM loja WHERE categoria = 'NOTEBOOK' ORDER BY nome ASC LIMIT 4");

if(mysql_num_rows($query) > 0){

    while($linha = mysql_fetch_array($query)){

        echo '<p><input type="checkbox" name="chk[]" value="'.$linha['id'].'" style="display:block"></p>';
    }
}

$query = mysql_query("SELECT * FROM loja WHERE categoria = 'Smartphone' ORDER BY nome ASC LIMIT 4");

if(mysql_num_rows($query) > 0){

    while($linha = mysql_fetch_array($query)){

        echo '<p><input type="checkbox" name="chk[]" value="'.$linha['id'].'" style="display:block"></p>';
    }
}

?>

<input type="submit" name="submit" value="Excluir Selecionados">

</form>

Then to delete

<?php
if(!empty($_POST['chk'])){

    $chk = $_POST['chk'];

    foreach($chk as $item){

        mysql_query("DELETE FROM loja WHERE id = '".$item."'")
    }
}
?>

Some remarks

The function mysql_ has been deprecated, so I recommend that you use mysqli .

I've never used the do while function, but I always recommend doing the same as I did in the code: Use only the while() function

I do not know your knowledge with PHP, but you would save code and processing using funções (function) in PHP, so the code would get cleaner and faster.

Always use the <?php tag. When you migrate to another server, the short tag may not be active, so do not ever use a <?php headache)

    
17.10.2015 / 04:58
0

Because it happened after a server change, it is probably related to PHP on your new server.

  • In your current code, do you use short tag <?=$linha['id']?> short tag is enabled on your current server? If not, is your value="<?=$linha['id']?>" not returning empty for this reason?

  • I did not test, I suggest you do these tests to eliminate these possibilities.

        
    16.10.2015 / 23:26