How to Determine the Success of a MySQL DELETE Operation
When executing a DELETE statement in MySQL using PHP, it can be crucial to ascertain whether the operation was successful or not. This article explores the different methods to verify the outcome of a DELETE operation and provides code examples to illustrate the usage.
Using mysql_query
For SQL statements such as DELETE, mysql_query returns a boolean value: TRUE for success and FALSE for error. The following code snippet demonstrates this:
<code class="php">$sql = "DELETE FROM foo WHERE bar = 'stuff'"; $result = mysql_query($sql); if ($result === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record"; }</code>
Using PDO::exec
If using the PDO extension, the PDO::exec method returns the number of rows affected by the DELETE statement. A value of 0 indicates no rows were affected.
<code class="php">$statement = $pdo->prepare("DELETE FROM foo WHERE bar = 'stuff'"); $result = $statement->execute(); if ($result === 0) { echo "No record deleted"; } else { echo "Record deleted successfully"; }</code>
Other Approaches
An alternative method to ensure the deletion was successful is to check if the row exists before executing the DELETE statement. However, this approach introduces an additional query and may not be optimal for performance.
Best Practice
The most reliable method to determine the success of a MySQL DELETE operation is to use either mysql_query and check the return value or PDO::exec and check the number of affected rows. By following these recommendations, you can effectively handle DELETE operations and ensure their expected outcome.
The above is the detailed content of How do I verify the success of a MySQL DELETE operation in PHP?. For more information, please follow other related articles on the PHP Chinese website!