Delete only selected PHP checkbox

Asked

Viewed 1,708 times

0

I have a system that I did (I don’t know much about PHP) worked perfectly but after switching server stopped working the function of deleting only the selected checkbox, it simply deletes everything.

I search all of them from database and have display only the first 4 ID (usually are saved with error in Database - XML 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>

Clean_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);
}
}
?>
  • Only with this code can not explain this behavior. Even if short_tags is disabled it would not erase all records. It must be something else. error_reporting(E_ALL);

4 answers

1

Why don’t you organize the id in a single variable, and then run as a single query ? Another thing, you’re passing the identifier on the attribute value, is unnecessary when you already have that same value in the attributename.

To be honest, I don’t remember exactly, and I don’t know if, this is the right line of thinking, 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.

Of:

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

To:

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

In this part of the script, you could just 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 don’t know if this is a custom function, created by yourself, or if it’s just the old extension connecting Mysql, because if it is, I recommend you start using Mysqli or PDO.

mysql_query($sql_deleta);

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

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);
 }
}

?>

0

Use this and it will definitely 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 discontinued, so I recommend using mysqli.

I never used the function do while, but recommend to always do the way I did in the code: Use only the function while()

I don’t 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 tag <?php . When you migrate to another server, maybe the short tag not be active, not to have headache always use <?php :)

0

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

I also noticed that you create the variable $linha = mysql_fetch_assoc($dados); and then creates her again in the do {} while {}, I don’t know if it gets in the way of anything, I haven’t been tested, but I don’t know if it helps.

0

Because it occurred after server exchange, it is probably related to the PHP of your new server.

  1. If other errors appear, it may be that the PHP version of the new server is newer and functions used in your code are deprecated.

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

I haven’t run any tests, so I suggest you run these tests to rule out these possibilities.

Browser other questions tagged

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