How to erase data from the database?

0

I have this code to delete the data of the database in which the name is equal to the one chosen in the combobox, whose code And the second. But for some reason I can not figure out which one is not working. Can you 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>
    
asked by anonymous 02.07.2017 / 22:08

2 answers

1

Hello, Isabel!

In your combobox you are sending the value id 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 does not find a name that matches the id you are sending, it does not delete anything.

Then in your php you put the command DELETE:

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

I think that's it.

    
03.07.2017 / 00:09
1

It looks like your query delete is incorrect. The correct syntax would be:

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

without * (asterisk)

The * is used for query tags as a wildcard for all table fields. In query delete you want to delete a whole record line so there is no point in using it there.

Make sure this helps you!

    
02.07.2017 / 23:27