Home > Database > Mysql Tutorial > How Can I Reliably Check the Success of a MySQL DELETE Query in PHP?

How Can I Reliably Check the Success of a MySQL DELETE Query in PHP?

Mary-Kate Olsen
Release: 2024-12-04 06:23:12
Original
715 people have browsed it

How Can I Reliably Check the Success of a MySQL DELETE Query in PHP?

Determining the Success of MySQL Query in Modifying Database Tables

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.

Case Study: Deletion of Articles

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";
    }
}
Copy after login

Flaws and the Correct Approach

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();
Copy after login

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.

Additional Considerations

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template