Mysql problems with DELETE

Asked

Viewed 395 times

-2

I’m having problems in mysql when recognizing delete function

 $code = '1234';

 $conn = new PDO('mysql:host=localhost;dbname=data', 'root');
 $stmt = $conn->prepare('SELECT * FROM codes WHERE code='.$code.'');
 $stmt->execute();

 $result = $stmt->fetchAll();

   foreach($result as $row) {

 extract($id);

 $del = "DELETE FROM codes WHERE id = '".$id."'";

 //$id é o id da coluna do BD
   }
 }
  • Could you be more specific about your difficulties? What flaws are you talking about?

  • @cat , mysql does not return anything in the DELETE function I made a var dump in the variables and they return me, but it seems that the function does not work

  • 1

    That one extract($id) shouldn’t be extract($row)? And how are you executing the command DELETE? In question you just defined it as string, but did not execute it.

  • the pq of these two closing braces } ?

  • Only needed to execute $Conn->exec($del);

2 answers

1


You are placing the string with the code to be executed but did not execute it, add the lines below, below the $del variable

if ($conn->query($del) === TRUE) {
    echo "Apagado com sucesso";
} else {
    echo "Error ao apagar: " . $conn->error;
}
  • Thank you very much friend, I forgot that detail!!

0

If you need to go through a query to find the id you want to delete, do so:

$rs = $con->query(“SELEC id, nome, email FROM pessoa”);
while($row = $rs->fetch(PDO::FETCH_OBJ)){
  if ($row->email == '[email protected]' ) {
      $id = $row->id;
  }
}

To perform a DELETE with PDO:

$stmt = $con->prepare("DELETE FROM pessoa WHERE idpessoa = ?");
$stmt->bindParam(1, $id);
$stmt->execute();

Browser other questions tagged

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