Reputation: 2084
I have a problem with a php script.
I want to delete a record from my database so I used the execute()
method, and it should return false when there is no record with the code I pass as an argument, but it always return true despite of there is not any record with that code.
This is the script:
<?php
include('connexion.php');
//Récuperation des valeurs
$code = $_POST['code'];
if($code)
{
//Suppression de l'enregistrment avec le code = $code à m'aide d'une requête préparée
$req = $bdd->prepare('Delete from chambre where code_ch = ?');
$rowDeleted = $req->execute(array($code));
//Ou bien : mysql_query('Delete from chambre where code_ch = '.$code);
$supprimer = ($rowDeleted == true) ? 'OK' : 'notfound';
}
else
{
$supprimer = 'empty';
}
header('Location: supprimer.php?supprimer='.$supprimer.'&code='.$code);
?>
Upvotes: 2
Views: 157
Reputation: 25701
You're probably confused. The documentation for execute says:
Returns TRUE on success or FALSE on failure.
It doesn't say anything about whether a row was deleted or not. You probably want affected rows if you want the number of rows deleted. However even then it's possibly a bad idea to depend on that. e.g what if two calls to delete the same row happen at the same time?
You shouldn't care that delete has actually deleted a row, only that the row you were trying to delete is no longer there.
Upvotes: 0
Reputation: 12635
A PHP PDO object will (correctly) return a success/true value for deletion on ZERO rows. One way around this is to use something like $pdo->rowCount()
to see how many rows the PDO affected. If you are trying to remove rows, you should consider a result of 0 from $pdo->rowCount()
to mean that you did not successfully delete the row you wanted to.
Upvotes: 2