In PHP, to ascertain the success of a MySQL query that aims to modify table data, one faces the dilemma of identifying any potential errors or assessing the impact of the operation. This article addresses how to retrieve accurate information about the outcome of such queries.
Consider the following PHP code snippet that attempts to delete an article from a database:
if($cmd=="deleterec"){ $deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?"; if ($delRecord = $con->prepare($deleteQuery)) { $delRecord->bind_param("s", $pk); $delRecord->execute(); $delRecord->close(); echo "true"; } else { echo "false"; } }
Initially, the code above only verifies whether the SQL statement is prepared correctly, failing to check if the record deletion was successful.
To resolve this, consider the following modification:
echo ($delRecord->affected_rows > 0) ? 'true' : 'false'; $delRecord->close();
The expression $delRecord->affected_rows provides the number of rows affected by the query. By checking if it exceeds zero, we can determine if any records were deleted successfully.
While this approach checks the query execution outcome, it's crucial to note that the JavaScript code receiving the result string from PHP must be configured to handle 'true' or 'false' appropriately to update the page via AJAX. Further investigation may be required to address any issues encountered during this process.
The above is the detailed content of How Can I Reliably Check the Success of a MySQL DELETE Query in PHP?. For more information, please follow other related articles on the PHP Chinese website!