0

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>");
 }
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
  • One `}` too much! Typo mistake? Also in a `DELETE` statement i would sugguest you to use `LIMIT`! – Rizier123 Oct 28 '14 at 14:45
  • **WARNING:** you code is open to sql injection attacks and `mysql_*` are deprecated, use `mysqli_*` instead. – Think Different Oct 28 '14 at 14:45
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 28 '14 at 14:45

3 Answers3

4

$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.

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
2

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>");
}  
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
0

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)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335