Reputation: 31
When I delete a record from table, I have 8 columns in the table and if more than 8 is entered it must be showed that nothing was deleted. However every number that I give, I get the same response "deleted successfully". This is my code:
$query = "DELETE FROM `order` WHERE orderId = '$_POST[id]'" ;
$result = mysql_query($query);
if(! $result )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
Upvotes: 0
Views: 75
Reputation: 943561
You are testing if your query ran successfully. It can be successful if it deletes one row or if it deletes none.
Use mysql_affected_rows
to determine if you've deleted any rows.
(You'd be better moving to a more modern API though)
Upvotes: 0
Reputation: 21446
You can use mysql_affected_rows
$query = "DELETE FROM `order` WHERE orderId = {$_POST[id]}" ;
mysql_query($query);
if(0 == mysql_affected_rows()){
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}else{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
Upvotes: 2
Reputation: 17797
$result
will be a valid result, even when your query won't affect any rows. Use mysql_affected_rows()
to check if you deleted anything.
$result = mysql_query($query);
if( mysql_affected_rows() == 0 )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
side note: the mysql_*
functions are deprecated. Don't use them to write new code, especially when you are learning. Use mysqli_*
or PDO instead.
Upvotes: 4