62

Using PHP, I am trying to delete a record, but I want to check if it was successful or not. Is anything returned from a successful DELETE FROM foo where bar = 'stuff'?

Alternatively, do you know any other ways to check if a DELETE was successful? Or am I better off just making sure the row exists before I delete it? I am trying to avoid another query if possible.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Jamison Dance
  • 19,896
  • 25
  • 97
  • 99

4 Answers4

69

Assuming you are using mysql_query:

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

If you are using PDO::exec, then the manual says this:

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.

Don't want to answer snipe, but since this was selected as the answer, I should note that mysql_query will return TRUE even if the query did not actually remove anything. You should use mysql_affected_rows to check for that.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
41

Additionally, if you care about the number of rows that were affected:

[Use] mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

biggusjimmus
  • 2,706
  • 3
  • 26
  • 31
  • 3
    Beat me! Checking that this is > 0 is helpful, as mysql_query() will return TRUE if the query was properly formed but didn't delete anything. – ceejayoz May 28 '09 at 18:19
  • @ceejayoz Could you please clarify that it did not delete anything because there was nothing to delete or because of some error? – MaxZoom Nov 16 '17 at 15:03
  • 1
    @MaxZoom If there's an error, `mysql_query` will return `FALSE`. If there's nothing to delete, `mysql_query` would return `TRUE` and `mysql_affected_rows` would be `0`. That said, you shouldn't be using `mysql_query` **at all** anymore. – ceejayoz Nov 16 '17 at 15:07
18

you could try this for your php code, placed after your query runs:

if (mysql_affected_rows() > 0) {
    echo "You have successfully updated your data.<br><br>";
}
else {
    echo "The data you submitted matched the current data so nothing was changed.<br><br>";
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
ryan
  • 189
  • 1
  • 2
0

For other types of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

Yaseen Ahmad
  • 1,807
  • 5
  • 25
  • 43