How to delete data from database?

Asked

Viewed 157 times

0

I have this code to erase the data from the database where the name is the same as the one chosen on the combobox, whose code and the second. But for some reason I can’t figure out which one isn’t working. They can help me?

....
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['botao_apagar']))
{
$cbnome= trim($_POST['cbMedicos']);
$stmt = $conn->prepare("DELETE * FROM Medicos WHERE nome= '".$cbnome."' "); 
$stmt->execute();

// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
}

}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

combobox code:

<label for="cbMedicos">Selecione um M&eacute;dico</label>
<select id="cbMedicos" name="cbMedicos">
<option>Selecione...</option>

<?php while($prod = $data->fetch_assoc()) { 
    echo '<option value="'.$prod['txtid'].'">'.$prod['txtNome'].'</option>';
    $meujson[$prod['txtid']] = $prod; // coleciona as linhas no $meujson


}
?>
</select>
  • 1

    Actually it is taking the id of the combobox and not the name. If so replace value="'.$prod['txtid'] for value="'.$prod['txtNome'] or in your query you delete by ID

2 answers

1

It seems that your query delete is incorrect. The correct syntax would be :

"DELETE FROM Medicos WHERE nome= ' ".$cbnome." ' " 

without the * (asterisk)

The * is used for query tags as a wildcard for all fields in the table. In query delete you want to delete an entire line of record so there is no sense of using it there.

If it helps you!

  • wildcard = wildcard or all fields in the table! = P

  • Entedi, thank you very much ;)

  • @Rafaelsalomão still doesn’t work

  • Do the following before your code: $stmt = $Conn->prepare("DELETE * FROM Medicos WHERE name= '".$cbname."' "); put this : echo "DELETE * FROM Medicos WHERE name= ' ". $cbnome." ' "and post here the answer!

  • Also check that in your form the button for the post has the name property set to "boot_delete" if it is not, it is likely that the delete routine is not running!

1


Hello, Isabel!

In your combobox is sending the id value and in delete you are trying to delete by name.

 echo '<option value="'.$prod['txtid'].'">'.$prod['txtNome'].'</option>';

If you want to delete by name, then send the name in value

echo '<option value="'.$prod['txtNome'].'">'.$prod['txtNome'].'</option>';

Your code even works, but since it doesn’t find any name that matches the id you’re sending, then it doesn’t delete anything.

Then in your php you put the DELETE command:

DELETE FROM Medicos WHERE nome= '".$cbnome."' "

I believe that’s it.

Browser other questions tagged

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