Home  >  Article  >  Backend Development  >  How to Ensure Successful MySQL Deletion Queries in PHP?

How to Ensure Successful MySQL Deletion Queries in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 13:31:02648browse

How to Ensure Successful MySQL Deletion Queries in PHP?

Checking the Success of MySQL Queries for Database Modification

In PHP, it's essential to verify the success of database-modifying queries to ensure data integrity. Let's examine a code snippet that demonstrates how to delete a record from a MySQL table and return a status message based on the query's outcome.

The code below executes a deletion query:

<code class="php">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";
    }
}</code>

However, this code only checks if the statement is prepared correctly. It doesn't verify whether the deletion was successful. To address this, you can use affected_rows to check if a record was affected:

<code class="php">...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();</code>

Remember to handle the response in your JavaScript code accordingly to update the page.

The above is the detailed content of How to Ensure Successful MySQL Deletion Queries in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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